This post originated from an RSS feed registered with Java Buzz
by dion.
Original Post: AOP Kata: Reusable Aspects
Feed Title: techno.blog(Dion)
Feed URL: http://feeds.feedburner.com/dion
Feed Description: blogging about life the universe and everything tech
There are certain aspects that are ripe for reuse. There are various levels of reuse of course (totally generic: Log4J, company-reuse: YourCompanyLogger, etc).
A common pattern that you run into, (we use it in aTrack. Ramnivas has it in his book, etc) is that you want to apply some advice, but only to a subset of your code.
The simple way to do this is to use the template pattern:
First, define the abstract aspect which does most of the work, but leave open a scope() pointcut:
public abstract aspect PolicyEnforcement {
pointcut printing():
get(* System.out) || get(* System.err) ||
call(* printStackTrace());
declare error: scope() && printing():
"Our policy enforces the fact that you have to print via our logger";
declare warning:
call(Exception.new()) ||
call(RuntimeException.new()) &&
scope():
"constructing exception without a cause.";
}
Now, create a concrete aspect which provides the scope:
public aspect DionsPolicyEnforcement extends PolicyEnforcement {
protected pointcut scope() : within(com.almaer..*);
}
In this example scope() was used, and is common... however you can of course create and abstract pointcuts which make sense for your problem, and have other classes provide those impls. You will often find common pointcuts such as scope(), and you will create your own within your projects.