Sunday, January 17, 2010

Separating Code Concerns using AOP

One of the new assignments I took is designing guidelines for separating the code concerns in .net applications.

Let's look at the example to understand what problem needs to be solved.
The following method retrieve products from the database.

public
List<Product> GetProducts()

{

Step1: Create Connection with the database

Step2: Call Stored Procedure to fetch the records.

Step3: Return list of products.

}

As we go on improving our code, we need to perform other activities like:

  1. Authorization: whether the current user has rights to fetch the complete product list
  2. Activity Capture: to log the activity performed by the user
  3. Caching

In order to implement this, we start incorporating the code in the above method as shown below (Example for Caching, Authorization, and Activity Capture):

public
List<Product> GetProducts()

{

Perform Activity Capture: Concern(Activity Capture)

    if( User is Authorized) Concern(Authorization)

    {

        if(Data is in Cache) Concern(Caching)

{

    Return data from cache

}

else

{

Create Connection with the database     

            Call Stored Procedure to fetch the records.

            Store the result in Cache.

            return the list of products

}

}

}

We created "GetProducts" method to retrieve Products but now start adding more concerns to it (marked in red). These concerns should be removed from the body of this method. This type of programming is called Aspect Oriented Programming (AOP).

Unfortunately .Net doesnot have inbuilt support for AOP. You need to use reflection a lot in order to perform this separation, however that would have negative impact on run-time performance of the applications. There are some very good frameworks that support AOP. In this blog, I will be discussing two approaches to do AOP in .Net

PostSharp: This framework uses Attribute Programming to separate concerns. Let's look how our above method will be written using PostSharp

[Authorization]
[Caching]
[ActivityCapture]
public
List<Product> GetProducts()
{

Create Connection with the database

    Call Stored Procedure to fetch the records.

    return the list of products

}

The body of the above method contains code only related to fetching the products and all other concerns are placed as attributes on top of the Method. PostSharp allows you to write your own attributes. You can specify the code that needs to be performed before or after the execution of the method body. Postsharp then does the compile time weaving to place the code at appropriate location.


You can download sample code that contains Authorization performed using PostSharp.

For more details on PostSharp visit: http://www.postsharp.org/

Keep looking into this blog for update on this topic.

No comments:

Post a Comment