Friday, July 17, 2009

WTF is AOP?

When I first heard about AOP the story have unfolded pretty much the same way as when I’ve read about Spring framework for the first time. The issue with understanding what IoC is for was that it looks very interesting, but complicated. And probably one should have some sort of insight so see any benefits behind all the complexity he (she) is exposed to while reading the documentation.

With AOP the story is the same. “What are my benefits?” – is the very first question I’m asking any book or article that is telling me about Aspect, Advises and Joint-points. And usually I have to patiently read through several more boring definitions when the author gets to the point. So I’m going to save you some of your precious time. Let me try to explain what AOP is and how you can benefit from it, putting it as simple as possible.

When you write your code, besides main functionality, you usually need to do auxiliary things, like logging, security stuff (or put it nerdy: authentication and authorization), and you might need something like transaction handling. Without AOP you most likely will end up doing this things right next to your “important code”. And there are several issues with this:
Methods containing your “important code” will be overloaded with auxiliary code and will be harder to read and understand.

  1. If you change the way you control user’s access to the system or the way you do logging or transaction handling, you’ll have to change it in each and every place you are doing that.
  2. When and if you start reading on about AOP you will see such words as scattering and tangling, which also refer to such “bad” functionality.

So AOP is aimed to reduce your pain while dealing with the issues mentioned. The idea is that any kind of auxiliary functionality is extracted into separate code which is going to be applied to any existing model, so that code that is already in that model doing the same things can be removed. And this extracted code is called Advice (don’t ask me why).

Then you define where you want to call this Advise from. I.e. you might want to write logging messages before a specific method call. This place will be called Pointcut. And all together with Advice this will form Aspect.
You can see how it works with logging in my previous post “Using Spring AOP to trace invocations”.

1 comment:

mhaller said...

my $0.2 on AOP-based logging: the usefulness of generic log statements ("methodIn", "methodOut") is -- zero.

please let me know how you would define Advices for such log statements:


public void init() {
doInitStuff();
Config config = loadConfig();
log.info("Config loaded from " + config.getFile());
doMoreStuff();
log.info("App started in ...ms");
}


AOP-logging produces very generic things and all you get is this:

123ms methodIn Main.init()
124ms methodOut Main.init()

Where is the valuable information in such output?