Tuesday, May 27, 2014

Aspect-oriented Programming (AOP) - Introduction - 2

In the previous post AOP - 1, I have started describing Aspect-Oriented Programming, that is, a paradigm that allows defining crosscutting concerns modularly. In particular, we have mentioned that it contains a query-like expression defining where the aspect should be applied, and the code representing the actual concern. In order to represent a crosscutting concern there may be several of such pieces of code, each called advice. The query expressing the locations is called pointcut and the actual locations that may match a pointcut are called joinpoints.
Each advice has a type: before, after or around. A before (or after) advice indicates that the code within the advice should be executed before (or after) the joinpoint matching the pointcut. An around advice allows changing the parameters of the original joinpoint, and even making the original call zero or more than once.
Some first (simple) examples are:
1)
before(): call(void *.m(..)){
  System.out.println("before calling m");
}

2)
after(): call(void *.m(..)){
  System.out.println("after calling m");
}

3)
void after(): call(void *.m(..)){
  System.out.println("before calling m");
  proceed();
  System.out.println("after calling m");
}

In the first example, before calling to any void method m (belonging to any class, with any set of arguments), the message "before calling m" is printed.
The second example is similar, but only prints the message after m has been called (and returned either successfully or because of an exception)
The third example surrounds the call with the two messages.

No comments:

Post a Comment