Aspects and Decorators

time to read 3 min | 546 words

There has been some discussion recently on the Castle about Aspect Oriented Programming* and their usage in production applications. I thought about using aspects for logging & security in my current project. But I decided against it. The reasons varied from not wanting to add more new stuff to an already complex project, other developers who would use the code, and ease of debugging/testing.

Instead, I used this approach:

The Container class is the central axis of my project, it binds together many services and allows easy access to the functionality of the application. The IRepository<T> interface is a generic interface for accessing and saving data, but with a twist. The nice thing about this approach is that I can specialize for each case independantly, and yet use a common approach where it is needed.

Okay, enough with the buzzwards, what does it mean? It means that I can use this interface for objects that I create I persist using ActiveRecord/NHibernate, for values from a resource files, etc. I'm using it extensively to avoid having to special case my code for each and every object type that I want to use.

An advantage of this approach is that I can now use decorators to provide the usual benefits of AOP. I have decorators that handles security, logging, transaction etc. I find that it is much easier to explain to people what is happening that way, since I can avoid telling them to ignore the man behind the curtain.

Two personal stories, before the end:

  • I had a bug in my decorator, where I leaked a transaction. It took me a while to figure out what was happening, (random errors about timeouts because the relevant rows were locked), since I never even looked at the decorator. When I debugged it, it suddenly put me in code that I recently chucked off as complete, and it was a two minute fix to do. I can imagine how hard it would have been if I couldn't debug that, or that it would happen completely transperantly.
  • I've a ineresting security problem, I need to check two permissions (and two seperate actions) for a single action. I'm not sure how I would handle that using aspects, but I'm planning to create a specialized decorator for that case, and the rest of my code will remain blissfully unaware of it.

This is not meant as an attack on aspects. If you've been following my blog for a while, you probably figured out that the less I need to do, the happier I am. Aspects certainly provide that, but they come with their own share of problems, which I'm not ready to deal with right now. Decorators are well understood and easy to explain, and it's very easy to generate the skeleton code via ReSharper to delegate to the next item, and add the custom operations that I'm interested in.

* Just to note, Aspect# is a Castle Project.