Search This Blog


Monday, December 22, 2008

AOP and PostSharp

Every competant programmer knows about OOP- Object Oriented Programming, but what about AOP-- Aspect Oriented Programming

AOP is a programming paradigm that emphasizes on the separation of cross-cutting concerns. For programmers, a lot of times when they are writing business code, they are also mixing in non-business code, such as security concern, logging mechanism or even profiling code. Different concerns are mixed in a method, and make the code harder to read and maintain.  

AOP separates different concerns into distinct part, making the code more modular. OOP fails to solve the Single Responsibility Principle problem, but a well written AOP application should have only a single responsibility for each object or method. 

Unfortunately, a lot of the languages, such as Java, C#, C++ don't natively support AOP. All that exists are just AOP frameworks that help one to write better AOP applications. In Java we have AspectJ,  an extension of the Eclipse IDE. In .Net there are a few frameworks; some of them have became abandonware, but some of them are still active and updated regularly. Out of those, PostSharp stands out from the crowd. 

PostSharp provides AOP mechanism by using attributes. You specify what you want to do before or after (Point Cut) a method ( Advice) in a separate class, and apply the relevant attributes to that class. So instead of doing your logging inside your business class, which inevitably clutter up your code and make them painful to read, you tranfer the logging mechanism to another class and let the business class to do only a single thing, namely processing business requirement.

As mentioned before, .Net framework doesn't support AOP natively, so what PostSharp is rather ingenious; it post-compiles your Aspect and weaves it into the MSIL code, so to the JIT it's still the same old MSIL code without anything fanciful. But to us the developers the separation between different concerns are important from maintenance perspective. No more logging in your main class, no more authentication, no more exception handling; what is there is the meat of the application. Isn't that great?

This is a screenshot of the generated MSIL code:

I am now trying PostSharp. The documentation is superb, and the examples are easy to use, and the forum response is quite fast. Quite an accomplishment for Open Source Software! The only thing is that it can't handle event firing, yet. 

I am going to spend the next few days playing with PostSharp, in the mean time, do visit the website and download a copy and have a try!


Lior Friedman said...

Ever thought about using Isolator AOP capabilities?

Soon Hui said...

Lior, to be honest, I have never thought of that :(.

But I am not sure whether it's advisable to use Isolator in production code or not.