I was going to buy a book on Aspect Oriented Programming, but all of the books I can find use AspectJ, and I don't currently use Java for anything. So I went looking for online resources about the principles of AOP and found some good stuff:
- Gregor Kiczales describes AOP to Google
This is excellent. It starts a little dry - like every good thinker, he's pedantic in laying down his groundwork. But in the last half hour, after he's described the concepts of AOP, he goes on to describe some of the potential applications and you'll start to see, if you hadn't already, that this is Teh RoX0rz. - Gregor Kiczales's 1997 paper on AOP (download PS or PDF on the right)
I went ahead and ordered a book that uses AspectJ, but really I'm interested in applying AOP principles to Ruby programs. [1] [2]
If you've heard of AOP but haven't looked into it yet, don't think that AOP is trying to be a silver bullet supplanting OOP. Kiczales has OOP continuing to be the "primary decomposition" for most software designs. AOP is a "secondary decomposition" providing a way to formalize the parts of the solution that don't naturally decompose into an object model, and then cleanly graft their calls onto the object hierarchy without having to tear the whole thing apart and put it back together. How many of you have worked on an object-oriented design that had a "Utility" class which was a bag of miscellaneous yet essential functions? Yeah, that. AOP brings order, abstraction, and flexibility to the bag o' functions, and also makes it super easy to add new calls wherever they are needed.
To me, the most compelling example is the example of adding logging to an established system. Let's say you inherit a project that has 50 classes and each class has a method called log_message(). But, for whatever reason, log_message() is defined independently in each class. Further, the implementation of log_message() is woefully insufficient in 48 of the 50 classes. Normally, what do you do? You check out all 50 classes and edit their log_message() implementations one by one. Probably, since you're at it, you'll try to factor out the commonalities, but either way, you're editing 50 classes. But with AOP, you can define a new Logger aspect and then define a pointcut pattern that intercepts any call to log_message() from any of the 50 classes and invokes your Logger in place of, or in addition to, log_message() itself.
Another interesting example is the factory example. Say you have 3 or 4 classes with constructors, but these constructors are guarded by a Factory class and should not be called from outside the Factory. (Think singletons.) You could probably do something with protected to enforce this, but that can lead to brittle dependencies in your class hierarchy. With AOP, you can lay pointcuts over all of the constructors, and throw an error if the caller isn't coming from a method of the Factory class.
No comments:
Post a Comment