I have class with many methods:
public class A {
public string method1() {
return "method1";
}
public string method2() {
return "method2";
}
public string method3() {
return "method3";
}
.
.
.
public string methodN() {
return "methodN";
}
}
I would like to add call to doSomething() in each method, for example:
public string methodi() {
doSomething();
return "methodi";
}
What is the best way to do so? Is there any suitable design pattern?
Instance methods are built functions into the class definition of an object and require an instance of that class to be called. To call the method, you need to qualify function with self. . For example, in a class that contains functions first() and second(), first() can call second().
Calling a method is like accessing a field. After the object name (if you're calling an instance method) or the type name (if you're calling a static method), add a period, the name of the method, and parentheses. Arguments are listed within the parentheses and are separated by commas.
We can call a method from another class by just creating an object of that class inside another class. After creating an object, call methods using the object reference variable.
The Function which calls another Function is called Calling Function and function which is called by another Function is call Called Function. How does Function execution work? A stack data structure is used during the execution of the function calls.
This is a typical use case for AOP (aspect oriented programming). You'd define the insertion points for the method calls and the AOP engine adds the correct code to the class file. This is often used when you want to add log statements without cluttering your source files.
For java you could add the aspectj library
For C# and .NET have look at this blog. Looks like a good starter.
Using AOP is already a good answer, it was my first idea too.
I tried to figure out a good way doing it without AOP though and came up with this idea (using the Decorator pattern):
interface I {
String method1();
String method2();
...
String methodN();
}
class IDoSomethingDecorator implements I {
private final I contents;
private final Runnable commonAction;
IDoSomethingDecorator(I decoratee, Runnable commonAction){
this.contents = decoratee;
this.commonAction = commonAction;
}
String methodi() {
this.commonAction().run();
return contents.methodi();
}
}
You could then decorate the construction of A (which implements I):
I a = new IDoSomethingDecorator(new A(),doSomething);
It is basically no rocket science and in fact results in more code than your first idea, but you are able to inject the common action and you separate the additional action from the class A itself. Further, you can turn it off easily or use it only in tests, for instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With