The basic idea behind AOP is separation of concerns. By "concern" I mean, roughly, a "bit of functionality". You want all you logging in one place. You want all your DB functionality in one place. You want all of your persistence layer in one place. Etc.
The basic idea of AOP is that decomposition into classes in a classic OO design/implementation can miss some separation of concerns.
The classic AOP example is logging. If you have a system where you are required to log each method entry and exit you need to do something like:
sub foo {
my $self = shift;
$self->logger->log('entering foo');
....
$self->logger->log('exiting foo');
};
to every method. This has two problems:
- It's a lot of monkey coding. Easy to make mistakes. Easy to miss a method out.
- The "concern" of "every method should log entry and exit" is spread out over the entire codebase. It isn't in one location. If you decide that you only want to log method entry you have to go change every method call.
In AOP you can have a single aspect that says "add this logging code to every method". No monkey coding. No possibility of missing anything. The concern is documented in one place. If you need to change what is logged, or what methods/classes logging should happen in, you only have to change one thing.
Introduction to Aspect Oriented Programming with AspectJ has an overview of some of the Jargon, although (obviously) Java oriented. There is also an mp3 of the lightning talk that Marcel Grunauer gave on Aspect at YAPC::North::America 2001.
AOP can be useful in static languages since it can provide you with a lot of additional flexibility (e.g. you can use AspectJ to add mixins to Java). They are of less relevance to more dynamic languages - especially those with a decent meta-class system. Although, on the Java side, aspects are a compile-time concept so they can be very efficient.
AOP can also make testing and debugging harder (IMO).
I have occasionally found AOP useful in debugging. For example Fun with Hook::LexWrap and code instrumentation could be viewed as AOP. |