I’m currently studying Aspect-Oriented Programming and while I was trying to practice a little bit, I realised I was designing different methods in the same aspect and I started wondering if this is the best way to do it, or if I should create different aspects for different methods.
I’ll try to explain more what I did:
I had 2 classes:
- Calculator Class had several methods such ass add, multiply, negate, reset, etc.
- AOPmain Class.
I created another class ( ReturnMessage class) to be an aspect, and in this class I created 2 methods – as you can see in the code below) (One is applied in a half of the methods found in the Calculator class, and the second one for some of the other methods in that same class – Calculator).
My question is: is it a good practice, to write several methods in an aspect to interact with other methods or it would be better to create different aspects for it?
Here is the code of my aspect:
@Aspect
public class ReturnMessage {
//the joinPoint is used to get the method names and args.
@Before("execution(public void *(double))")
public void returningMessage( JoinPoint jp) {
String method = jp.getSignature().getName();
double value = (Double) jp.getArgs()[0];
System.out.println("Going to "+method+" "+value);
}
@Before("@annotation(lala)")
public void returnMsg2(MyAnnotation lala) { //<-- should I create another aspect to put this method?
System.out.println(lala.msg());
}
}
I believe it’ll be interesting not only for me, but for all users of stackoverflow who are starting programming in aop, so I hope you guys to be pacient.
I would create an Aspect for each cross cutting concern i want to track. It is ok, to have multiple pointcut/method in your aspect.
You could have an Aspect responsible for logging, one for metrics etc…
I found this link very helpful when i worked with AoP to measure the perf. of an existing app.
It talk about aspect over existing codebase, but the it can be applied to any case.
Applying AspectJ to an Existing Codebase