Aspect Oriented Programming is a methodology, like OOP, that has been around for a few years now. But it is sadly not as known as OOP. I myself came across it only a few weeks ago and I was fascinated by the whole idea. AOP targets mostly on the implementation of crosscutting concerns like logging and tries to seperate the whole crosscutting logic from your actual code. As far as I know it now is it not there to substitute OOP or other methodologies but to work with them hand in hand. The problem AOP faces is that it is something new and has first to be accepted in the community. The other issue is that you need a programming language that supports AOP like AspectJ for Java. Even though you could probably partly implement it with a “few” workarounds in a non-AOP language.
To show you what AOP is all about let’s look at the logging example. If you write a method that logs you probably do it the following way:
class YourClass {
public int doSomething() {
logger.log(”Before: execution(YourClass.doSomething())”);
…
logger.log(”After: executeion(YourClass.doSomething())”);
}
}
(Your log output maybe looks a little different.)
What’s wrong with this?
Well, wrong are the two calls of the logger.log() method before and after the execution of the doSomething() method because it has nothing to do with the primary thing the method tries to accomplish. The problem is that you cannot handle logging easily in a better way using just plain OOP. That’s the time when AOP comes in. To express it in code:
// the actual logic
class YourClass {
public int doSomething() {
…
}
}
// aspect “code”
aspect YourAspect {
before execution of method doSomething() in class YourClass do the following: logger.log(”Before: execution(YourClass.doSomething())”);
after execution of method doSomething() in class YourClass do the following: logger.log(”After: execution(YourClass.doSomething())”);
}
If you’d now compile the aspect named YourAspect the aspect and the class would be woven together and you’d get the same result as in our first example.
This looks/sounds a little scary for the first time. Partly because it isn’t real code and maybe partly because it is something new and unknown and although partly because I’m not a good writer of examples and the above “code” is a little awkward written so don’t be scared. The cool thing is that your actual logic is now almost completely seperated from the logging code and you could just wipe off the whole logging code without modifying your actual logic.
That’s it for now. I hope you got the basic idea. But there is much more to come. So stay tuned.
