Aspect Oriented Programming

In object oriented programming, each object or class is made up of some properties and behavior. For example an Employee object might have properties like employee id, name etc and behavior like works.

so a simple Employee class would look like

public class Employee {
int id;
String name;

public Employee(int id, String name)
{
this.id=id;
this.name=name;
}

public void work()
{
System.out.println(“Employee:”+ name+” is working”);
}
}

But in real world a lot of things are happening around objects, for example lets say a bookkeeper needs to take a note of everytime an employee starts working and finishes working.

public class BookKeeper {

java.util.Date date= new java.util.Date();
/**
* This method records when employee has started working
*/
public void employeeStartsWorking()
{
System.out.println(“Employee has started working”+new Timestamp(date.getTime()));
}

/**
* This method indicates when employee has stopped working
*/
public void employeeEndsWorking()
{
System.out.println(“Employee has ended working”+new Timestamp(date.getTime()));
}

}

And my Employee class should be modified to

public class Employee {
int id;
String name;
BookKeeper bookKeeper=new BookKeeper();

public Employee(int id, String name)
{
this.id=id;
this.name=name;
}

public void work()
{
bookKeeper.employeeStartsWorking();
System.out.println(“Employee:”+ name+” is working”);
bookKeeper.employeeEndsWorking();
}
}

The challenge here is that my Employee should now be aware of BookKeeper and maintain its calls. Also it would need to actually handle error conditions (what if bookKeeper is null).

AOP or Aspect oriented programming comes to rescue here. Wikipedia states “In computing, aspect-oriented programming (AOP) is a patented[1] programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns.”

Cross cutting concerns are the functionalities which are distributed accross the application but are not part of any core module. So for example, we have employee class, manager class, consultant class all implemeting work and book keeper keeoing record. So Book keeper needs to be available to all these objects, though it is not part of their core functionality. AOP recommends to move these functionality out of class and provides methods and tools for this.

Some frequently occuring cases for AOP are logging (ever class has need for logging, but it is not part of core functionality), transaction management, authentication and authrization etc.

I will talk about implementation of AOP part in next post.