Friday, February 17, 2006

Diving into AOP

I've finally begun diving into AOP. I downloaded AspectJ 1.5.0 and am now reading the tutorial. I've just started, just finished reading the part on inter-type declarations, which is obviously quite powerful and dangerous at the same time. It allows you to add methods and instance variables into a class or set of classes. For example, if you want the Point class to have observers (taken from the AspectJ Programming Guide):

aspect PointObserving {
private Vector Point.observers = new Vector();

public static void addObserver(Point p, Screen s) {
p.observers.add(s);
}
public static void removeObserver(Point p, Screen s) {
p.observers.remove(s);
}
pointcut changes(Point p): target(p) && call(void Point.set*(int));

after(Point p): changes(p) {
Iterator iter = p.observers.iterator();
while ( iter.hasNext() ) {
updateObserver(p, (Screen)iter.next());
}
}

static void updateObserver(Point p, Screen s) {
s.display(p);
}
}

...it allows you to add similar behavior to a group of unrelated classes without resorting to inheritance. However, this also means that a class has behavior that's not declared in the class's definition. This feature can therfore go either way: It can make code more maintainable by making sure behavior is only declared in one place. Or, if used carelessly, it can make for spaghetti code unlike any spaghetti code the world has ever seen.

I'm eager to see how Eclipse makes tracing and debugging with AspectJ possible. Later...

No comments:

Post a Comment