A very brief introduction to AOP

I’m quite young, I’ve worked in only a few software projects, but in every one of them I’ve seen particular pieces of code repeating over and over again in every function or method. I’m pretty sure that you, as a developer, have faced the same problem. An example:

if (logger.isDebugEnabled()) {
logger.debug(“I'm a crunchy potato”);

Let’s imagine that you work in a company. Normally, you get paid at the end of every month (hopefully), but you don’t need to ask for your payment or care about how the money is deposited in your bank account.

So let’s imagine again that we have a simple function that calculates the sum of two numbers given as input, logs it with the snippet showed above, and then it returns the sum. Why should this function care about logging when it’s obvious that its main purpose is only to add two numbers? Do we need to ask for our salary when it’s not our duty as workers? We delegate this task to another entity (the company’s account managers, the bank workers…), so why don’t we do the same with our code?

Here is when Aspect-Oriented Programming (AOP) takes part. You could define the logging snippet as an aspect, that executes automatically when the main two number addition method is called, or in other customizable points without writing any logging code explicitly.

With the transformation of the logging method into an aspect, the main function gets to know nothing about any logger or stuff not related to it. This gives us:

  • Isolation from not related things in our code.
  • Accuracy in the duties of our methods.
  • Decoupling from common cross modules such as logging, security, transactionality…
  • Behavior modifications all along our architecture are made with a single change in some simple points at the code.

AOP has a very specific terminology (kind of weird) for every element:

  • Advice. What does the aspect do, and exactly when it has to be done.
  • Join point. Where in your code an aspect can be executed.
  • Pointcut. A single or many join points can be attached to an advice, this is known as the pointcut.
  • Weaving. When the aspects are applied, a new class is generated at runtime, compilation time or class load time, depending on the technology used.

We can play with aspects with an AOP framework like AspectJ or Spring for Java, or the AOP module for Node.js, for example.

I’ll write more about this topic when I’m less busy (or maybe not), so stay tuned if you’re interested. Also you can read more of this topic in the Wikipedia, of course.