domingo, 10 de noviembre de 2013

What is AOP (Aspect Oriented Programming)?

For me AOP is a all about avoiding repetitive code to support common functionally by replacing that functionality with simple declarations associated to a method, class or module.

Think about it for a moment, I'm sure there are a lot of common tasks that you have to repeat in your projects: logging, authentication, caching, transactions, locking...     Those are commonly called cross-cutting concerns. In the worse case you will have lot of lines of code duplicated in all your methods for that functionality,  in the best case you will have that code in a library and you will have only one 1 line of code in all your methods.    But 1 line of code is still infinitely more than 0 lines of code!!!

If we were able to define those functions in a declarative way it would be great.   We need a way to tell the compiler "Add logging to this method", "All the responses in the methods of this class can be cached", "Make sure this method is executed in a transaction"... but hopefully without having to put that code in the middle of the real code of our application.  Business logic of our service should be easy to read and maintain and not obscured with tons of lines implementing plumbing functionality.

Most of the modern languages have a way to add some information attached to classes and methods.   For example we have Annotations in Java, Attributes in C# or Decorators in Python.

It is very easy to define in Java an annotation saying @Logging that can be attached to any method or class, the problem is how to associate some behavior to those annotations.    This is completely language/framework dependent but taking Java as an example, we have different options:
* Code modifications: A pre/post compiler task will modify the source code or byte code to introduce the code associated with each annotation.
* Dynamic proxies: When using IoC the container can instantiate a proxy instead of the real object and that proxy will execute the code associated with the annotations.
* Middlewares/Filters: In some frameworks (like jersey) you have the concept of filters that are executed for each request and you can add specific filters that can check the annotations in the class serving the request.

// Pending (I'm lazy) adding an example

I have been using AOP for years without any idea of this terminology, but just for completeness.... When we talk about AOP we usually mention Joint points and Advices.  Joint points are the points where the code will be added (for example before the method or after the method) and Advices the actual code that will be added.   An aspect is the combination of Joint points and Advice.