Wednesday, November 22, 2006

Aspect Oriented Programming

AOP - Aspect Oriented Programming.

One of the main reasons to use OOP, is for the SoC (Separation Of Concern) - the ability to separate each "problem" into an object (class).

This approach is well-suited for most tasks, because many problems can be easily and naturally described by objects.

But sometimes there are aspects of the problem which can't be encapsulated: they somehow cut through the whole object model and you won't be able to take them out into separated objects - for example - (you guessed it) logging.

Although I've got only one logging class in my system, almost every other class needs logging abilities.

In my examples, I'm using the NAspect framework, although there are plenty of other AOP frameworks for .Net.

Defining Aspects

First off, I define the interface of my class, and mark the wanted methods as logging enabled:


public interface IMyTestClass
{
    [Log()]
    void DoStuff1(out int a);
    [CheckSecurity()]
    int DoStuff2([Parameter()] int a);
    [Log()]
    string DoStuff2(int a, [NotNullParameter()] string b);
    int SomeProperty { get; set; }
}



Now, in my code, I first need to configure my AOP engine:


IEngine c = ApplicationContext.Configure();




And request a new MyTestClass object from the engine:


IMyTestClass t = c.CreateProxy(typeof (MyTestClass)) as IMyTestClass;




And that's it – now I write my standard code with logging enabled:

t.DoStuff2(1);
t.DoStuff2(2);

The example I've shown here is prety simple and not complete, but it should let you a small glimpse at how AOP is looked like.

You can download the the code for the example here

As I said before, there are many AOP frameworks for the .Net framework out there, 2 of my favorites are: NAspect of the Puzzle Project and the Aspect# of the Castle bulk.

No comments: