Aug 17 2008

An Introduction To Aspect Oriented Programming

Category: AlexRobson @ 02:59

Part of Nvigorate's usefulness is attributed directly to it's use of PostSharp, an open source Aspect Oriented Programming library. Before I go into how PostSharp does it's thing, let's talk about Aspect Oriented Programming at a high level.

Aspect Oriented Programming is the design philosophy that allows you to write code which addresses a feature (generally referred to as a concern in AOP terms) that spans multiple functions and classes in your code. A good example of a concern in Nvigorate is checking method parameters for null arguments. A common best practice debate is whether or not functions should ever allow null arguments or simply provide enough over-loads. (I think it depends on the context of what you're doing) The Reflector class in Nvigorate provides common Reflection functionality through simple static functions. Due to the nature of the calls, a null argument in any of these calls would cause exceptions. Instead of having to write very tedious code that checks every parameter for null inside of all of the Reflector class's 55 public methods, I could use AOP to address this concern across all the methods at once. The code that would address this concern is called advice. Applying the advice code to multiple methods dynamically in AOP is called cross-cutting. Each location in the code that the advice gets applied is called a point-cut. The process of applying advice to all the point-cuts is called weaving. Unfortunately, the .Net framework doesn't really give us much to work with in order to pull this off. Currently, there are two popular approaches to weaving: compile time and run-time.

Runtime time weaving carries several performance hits in terms of both memory and runtime overhead as well as carrying some unpleasant inheritance implications as well. Personally, I'd rather spontaneously combust than use any of the popular runtime weavers that I've evaluated in the past.

Compile time weaving works by emitting the IL for the advice code dynamically into the resulting assembly. The reason this approach is so 'great' is that it's the automated equivalent of you copy/pasting the advice code into the point-cuts manually.

Now that all this terminology is floating around in your brain (like soup!) I can explain what PostSharp does. PostSharp is an open source compile time weaver which runs AFTER the initial build. This means once .Net's compiler completes compilation, it injects calls to your advice into the IL of all the point-cuts. It's fairly precise in that you can control (for the most part) where the actual call to the advice happens. In a follow-up post I'll be showing how to use PostSharp to implement the previous example.

Tags:

blog comments powered by Disqus