Simple AOP: introduction to AOP

February 13, 2009 at 12:46 PMAndre Loker

Aspect oriented programming (AOP) allows us to keep implement different concerns in isolation. In this article series I’ll describe ways to make use of AOP without much hassle. This first article serves as an introduction to AOP to those that are not familiar with aspect orientation.

Why AOP

If we analyse the source code software system we will soon realize that the different parts of the code can be grouped according to their responsibilities. For example some parts of the code are responsible for implementing business logic, other parts manage transactions, yet other parts are used to handle exceptions etc. In AOP terms those responsibilities are called concerns. The business logic is considered the core concern of the application, whereas the latter examples represent aspects that somehow interact with the core concerns. Because they interact with the core concerns, aspects are often called cross-cutting concerns. When we look closer at those interactions we can identify two problems:

1. Scattering

Scattering occurs if the same aspect has impact at many different places in the code. For example, logging or transaction management are often used at many different places in the code, but each time almost exactly the same way. This is problematic because it is harder to maintain scattered functionality.

2. Tangle

The second problem that often occurs is that of tangling concerns. At a given place in code – let’s say a single method – different concerns are present and interleaved. To give you an example, here’s a method that has the core responsibility to change the email address of a user identified by some  ID. Three concerns can be identified: the core concern (changing the email address) and two additional aspects (exception handling and transaction management). I highlighted the different concerns using different colours.

tangle

Tangling concerns are a problem because they bloat the code and distract from the core concerns. Here’s the same core concern without any extra aspects:

   1: public Result ChangeEmailAddressBusinessOnly(int userID, string newEmailAddress) {
   2:   var user = Users.GetUserByID(userID);
   3:   if (user != null) {
   4:     user.ChangeEmailAddress(newEmailAddress);
   5:     return Result.Success;
   6:   }
   7:   return Result.Error("User not found");
   8: }

Tangling also makes unit testing more difficult, because all the extra non-core concerns have to be considered during the tests as well, at least they have to be stubbed or mocked.

Using AOP to solve scattering and tangle

AOP tries to solve the two problems using the separation of concerns paradigm. With AOP the different aspects are described and implemented in isolation. Because the behaviour is defined once only and than applied automatically at all places of interest in the code, scattering won’t appear. And secondly, because aspects are defined in isolation the core concerns can be implemented without any intermingling aspects which solves the problem of code tangle.

Advices

The implementation of the behaviour is called the advice of the concern. Here’s an example of the advice belonging to the exception handling concern in pseudocode:

   1: someAdvice(context) {
   2:   try {
   3:     context.Proceed();
   4:   } catch(Exception e) {
   5:     if(ExceptionHandler.ShouldRethrow(e)) {
   6:       throw;
   7:     }
   8:   }
   9: }

In this example context.Proceed() would execute whatever has to be executed at the point where this concern is present. If that code throws an exception we can handle it.

Pointcuts

We must of course somehow define where the concern is present. This is defined by the so-called pointcut. A pointcut is a boolean expression answering the question “should this concern be applied here?” for every possible “here”. Now, what’s a “here”? A “here" in this context is every possible point in the code where a concern can possibly be applied. Those points are called join points. Examples are: “A call to a method named X” or “The assignment of a value to a variable”. What kinds of join points are supported depends on the AOP implementation and is defined in that implementation’s join point model. Adding pointcuts to our pseudocode example could look like this:

   1: pointcut ServiceMethods : call to any method of class Service
   2:  
   3: someAdvice(context) at ServiceMethods {
   4:   try {
   5:     context.Proceed();
   6:   } catch(Exception e) {
   7:     if(ExceptionHandler.ShouldRethrow(e)) {
   8:       throw;
   9:     }
  10:   }
  11: }

Now everytime we call a method of class  Service the advice will be executed. The call to Proceed() will in this case execute the method that is being called.

Advice types

Now that we have defined what is advised and where we can add the minor detail of when it is applied, because we have different kinds of advices. The example above uses a so called around advice. That is, the advice is wrapped around the joinpoint. It controls the moment when the joinpoint is executed explicitly by calling Proceed(). Other examples of advice types are:

  • before and after advices, which are executed before or after the execution of the joinpoint respectively. Those advices can’t explicitly define when the joinpoint is executed.
  • throwing advices, which are only executed if the execution of the joinpoint raised an exception
  • returning advices, which are only executed if the execution of the joinpoint did not raise an exception

Finally, here’s a fine-tuned version of our pseudo code example:

   1: pointcut ServiceMethods : call( Service.* )
   2:  
   3: around(context) : ServiceMethods {
   4:   try {
   5:     context.Proceed();
   6:   } catch(Exception e) {
   7:     if(ExceptionHandler.ShouldRethrow(e)) {
   8:       throw;
   9:     }
  10:   }
  11: }

By the way, I didn’t come up with this notation all by myself. It resembles the syntax used with AspectJ, which is more or less the most prominent (Java) AOP framework available. It has grown quite mature and if you’re interested in AOP I highly recommend to have a look at it. Yes - even it uses Java :-) 

Weaving

So, we have defined a bunch of aspects with their pointcuts and advices. The missing link is obvious: how do those advices get applied to the base code (the code containing core concerns)?  For this process – called weaving - several approaches exist, all with different pros and cons.

Compile time weaving

This approach is taken by AspectJ for example. An additional step is taken during compilation that inserts the advices into the source code or an existing binary assembly. This results in binaries that don’t look any different from conventional binaries.

Pros

  • the join point model can be very detailed (e.g. the assignment of a value to a variable)
  • performance wise there’s little overhead

Cons

  • weaving is static only, we can’t change aspects at runtime

Runtime weaving

With runtime weaving the aspects are woven into the base code – well – at runtime. There are different approaches to achieve this. Some implementations for example modify the runtime environment to support injection of code. A simpler approach is the creation of runtime proxies for advised objects.

Pros

  • no need for an extra compiler
  • aspects can be added or removed dynamically

Cons

  • depending on the implementation, the join point model can be rather limited

For this article series we’ll use proxy based runtime weaving: it is simple and in many cases sufficient.

Critical view

In principle AOP sounds promising: separation of concerns helps to concentrate on core concerns and keeps our code free of tangle and scattering. Where there’s light, there’s also shadow they say and this counts for AOP. If you look at the base code you can’t see at a glimpse which aspects are applied (except if you have tool support). Because the aspects are injected “invisibly” you might encounter unexpected runtime behaviour, especially if the aspects affect each other. Likewise, you have to be careful where the different aspects are advised to avoid some unintended application of concerns. Keep an eye on your pointcuts!

Also, AOP is generally not a first class citizen but an “artificial” extension to existing software environments the woven code comes with an overhead, especially with runtime weavers. Most business applications are I/O bounded, so whether a method call takes 1 microsecond or 1 millisecond does not matter much if the method itself takes 50 milliseconds to run. Just be aware that advising a join point in a performance critical loop might be something to reconsider.

Therefore – as with any tool – use AOP wisely. Use it when it makes sense, just don’t go crazy with your new toy.

Wrapping it up

This concludes my introduction to AOP. I haven’t covered all details of the topic (like inter type declarations or advice precedence). Still I’ve hopefully shown the need for and benefits of AOP well enough to have awaken your interest in the next parts of this series. Feel free to leave a comment for questions and suggestions.

In the next part of the series I’ll how we can use Castle DynamicProxy as a starting point for a AOP-esque separatio of concerns.

Other articles in this series:

Posted in: Tools | Other

Tags: ,

Pingbacks and trackbacks (5)+