0

I have twenty small methods (m1, m2, m3, etc..) in a class quite different between each other, and after every method i would like to do some common actions, like increasing some counters and in the case write those counters to a file. Let's call those actions ACT.

I know that I can create a method that does ACT, but then I need to call it from every other method. That is, from m1 I should call ACT as last method, from m2 I should call ACT as last method, and so on.

Is there a way to say "if someone call this list of methods of this class (i.e: m1, m2, m3 ...), please after that call that method (i.e: ACT) automatically" ? Because AFAIK is not possible.

1

1 Answer 1

3

AOP is good approach to solve your problem.

But I advice you to examine your class. Twenty small methods quite different between each other in a class is a little code smell. I think your class probably violate single responsibility principle.

http://en.wikipedia.org/wiki/Single_responsibility_principle

2
  • I would like to add to this and point out the Command Pattern, you can use this pattern with some interfaces to implement an AOP approach. This is geared towards C# but I am sure you could translate the knowledge fairly easy. cuttingedge.it/blogs/steven/pivot/entry.php?id=91
    – Tony
    Oct 14, 2014 at 20:14
  • Thanks for the links, my comment could be misleading. Depends on the "amount" of difference. For me could be, for example, that method1 write to a file only integers, method2 only strings, method3 only certain objects and so on, and after all i would like to count how many changes on the file were done (for example). But still i tried to keep the question abstract, one problem that i realize always late is that if i don't specify the question as "abstract" explicitly then details are important for who answers.
    – Pier A
    Oct 15, 2014 at 10:30

Not the answer you're looking for? Browse other questions tagged or ask your own question.