Thursday, June 12, 2014

Aspect-oriented Programming (AOP) - around advice

We have discussed before and after advice (AfterAOP - 2), it remains to talk about around advice. This kind of advice is very interesting because not only allows adding behavior before and/or after the original joinpoint, but also allows overriding the original behavior, or applying the original behavior multiple times.

For example,

public class C{

  public static void main(){
1    int y = addOne(0);
2    System.out.println(y);
  }

  public static int addOne(int x){
3    return x+1;
  }
}

public aspect A{
4  pointcut callAddOne(int x): call(* *.addOne(int)) && args(x)

5  int around(int x): callAddOne(x){
6    System.out.println("before calling");
7    int tmpValue = proceed(x);
8    tmpValue = proceed(tmpValue);
9    System.out.println("after calling");
10    return tmpValue;
  }
}

In the example, the around advice (line 5) is activated when the pointcut (line 4) matches a joinpoint. The only location in C where this occurs is in line 1, when addOne is called.
Then, the following things happen
i) when matching the joinpoint, the pointcut caputres x as the argument to the call (notices args(x) within the pointcut definition)
ii) the message "before calling" is printed
iii) proceed indicates to apply the original behavior. That is, we are actually calling to addOne with the value x (in the original call was 0, so this is the value within the advice).
iv) tmpValue obtains the return value of the call, in this case 1
v) we call again to the original method! but this time with the argument tmpValue
vi) tmpValue is updated to 2 (it was incremented by the second proceed)
vii) the second message within the advice is printed
viii) the value 2 is returned
ix) y (in line 1) receives 2 and gets printed.


Around-like advice are a very strong mechanism not only to add behavior before or after the original, but also to change the control flow, for instance by making the original joinpoint to be executed multiple times, or none at all! If within the around advice there is no proceed, then the original behavior gets overriden.

The Earth moves around the Sun (but doesn't override it :) )




No comments:

Post a Comment