Tuesday, 7 February 2012

Aspect-Oriented Programming



When thinking of an object and its relationship to other objects we often think in terms of inheritance. We define some abstract class; let us use a Dog class as an example. As we identify similar classes but with unique behaviors of their own, we often use inheritance to extend the functionality. For instance, if we identified a Poodle we could say a Poodle Is A Dog, so Poodle inherits Dog. So far so good, but what happens when we define another unique behavior later on that we label as an Obedient Dog? Surely not all Dogs are obedient, so the Dog class cannot contain the obedience behavior. Furthermore, if we were to create an Obedient Dog class that inherited from Dog, then where would aPoodle fit in that hierarchy? A Poodle is A Dog, but a Poodle may or may not be obedient; does Poodle, then, inherit from Dog, or does Poodle inherit from Obedient Dog? Instead, we can look at obedience as an aspect that we apply to any type of Dog that is obedient, as opposed to inappropriately forcing that behavior in the Dog hierarchy.

In software terms, aspect-oriented programming allows us the ability to apply aspects that alter behavior to classes or objects independent of any inheritance hierarchy. We can then apply these aspects either during runtime or compile time. It is easier to demonstrate AOP by example then to describe it. To start, though, it is important to define four key AOP terms I will use repeatedly:

  • Joinpoint—Well defined points in code that can be identified.
  • Pointcut—A way of specifying a Joinpoint by some means of configuration or code.
  • Advice—A way of expressing a cross cutting action that needs to occur.
  • Mixin—An instance of a class to be mixed in with the target instance of a class to introduce new behavior.

To better understand these terms, think of a joinpoint as a defined point in program flow. A good example of a joinpoint is the following: when code invokes a method, that point at which that invocation occurs is considered the joinpoint. The pointcut allows us to specify or define the joinpoints that we wish to intercept in our program flow. A Pointcut also contains an advice that is to occur when the joinpoint is reached. So if we define a Pointcut on a particular method being invoked, when the invocation occurs or the joinpoint is invoked, it is intercepted by the AOP framework and the pointcut's advice is executed. An advice can be several things, but you should most commonly think of it as another method to invoke. So when we invoke a method with a pointcut, our advice to execute would be another method to invoke. This advice or method to invoke could be on the object whose method was intercepted or on another object that we mixed in. We will explain mixins in further detail later.



Extracted From - http://msdn.microsoft.com/en-us/library/aa288717(v=vs.71).aspx

No comments:

Post a Comment