Saturday, August 1, 2009

AOP - Simple Example

Aspect Oriented Programming (AOP) promotes separation of cross-cutting concerns like logging, transaction management, security, etc from the components in a software system. The components may be performing these system services apart from the core logic they are entrusted with. These concerns tend to cut across multiple components in a system, hence called cross-cutting concerns of a system. These concerns introduce levels of complexity to your code as -
  • systemwide duplicated code for implementing these system concerns, necessitating multiple code changes if any of the concerns change
  • components are burdened with more code than that which deals with their core functionality
AOP modularizes these services and applies them declaratively to the required components in the system. Hence, components become more specific and cohesive. It covers the core application with layers of functionality without the application even knowing it exists.

Let us get a feel of AOP through a simple example.
A class People who sings praiseworthy songs about a class King. Let us see how it works without AOP.



Here, each time the King goes to a War, it must stop and tell his People to Praise him before he can start fighting the War. Similary, after the War, the King must remember to tell the People again to Praise him about his achievements.

Let us now introduce the concept of Aspect here and also, a configuration file praise.xml.


The functionality of the Aspect is defined in the bean referred to by the ref attribute. The aspect is made up of pointcuts and advice. Here, we declare a pointcut which is triggered by the execution of a startWar() method. Advices are provided in 2 forms here - before to call singBefore() method of People before the pointcut and after to call singAfter() method of People after the pointcut.

This simplifies the code in class King as follows:




reference: spring in action

2 comments:

  1. AOP (Aspect-Oriented Programming) Host Genics simplifies code by allowing cross-cutting concerns like logging or security to be handled separately from the main business logic, improving modularity.






    ReplyDelete