Tuesday, April 10, 2007

AOP-Aspect-oriented Programming

Why we need AOP

AOP lets the developer better separate tasks that should not be inextricably tangled in code like logging, Assigning login user id to Oracle Client Identifier, Exception handling etc.

What is AOP

Aspect-Oriented Programming (AOP) complements Object-Oriented Programming (OOP) by providing another way of thinking about program structure.

You can think of aspects as doing something around, before or after calls to groups of methods in your program.

Where can we use AOP

A great example is J2EE applications where you have to deal with all sorts of functionality that is really orthogonal to the business logic of your application (persistence, authorization, load balancing, transactions) but typically ends up mixed in to your code.

So you can avoid such code mixed up in your business logic code and the orthogonal feature like Logging can be used as aspect and it can be reused at different place (pointcuts) in your code.

Example

With out going too deep into any of the AOP terminology, let take a real time example and see how we can apply AOP using spring framework.

I was doing sample project to understand the JSF, spring and hibernate framework and I was using Oracle personal Express edition 10g.

Well, I slowly started the sample project and I had one of the requirement of auditing.

When ever user create a new row or updates row in database I have to track the date time and user id for that action.

I have database columns called create_dt_time, create_user_id, update_dt_time, update_user_id for this purpose.

Approach or options

One way to do this would be write code every where, where ever you have insert or update statement get the logged on user id and send to the insert or update sql statement as parameter and current date time as parameter.

Or if you are using Hibernate framework for your persistence, you can use the hibernate interceptor to write common logic to get the logged on user id and inject that to your domain object and Hibernate will help you to save or update that domain object.

Or the other way can be using AOP concept, which declarative and can be applied to all or some of the methods.

There can be many ways to solve/implement the above problem domain and right now I am not pointing the advantages or disadvantages of different approaches.

Right now our goal is to learn the AOP using spring framework.

Let's see how to implement this using spring AOP.

Aspect - Think of this as the general feature you want to apply globally to your application, in this example is our Auditing.

Advice - A chunk of code that is invoked during program execution, and is a piece of the logic for implementing your aspect. This is the first important piece of a Spring AOP aspect implementation, compare advice implementations to the decorator pattern.



Joinpoint - A place in the code where an advice should be executed. Spring's AOP only supports method invocation. So by default this is on method invocation.

Pointcut - A pointcut is a set of many joinpoints where an advice should be executed. Spring allows only method invocation, so a pointcut is just a set of methods that, when called, should have advices invoked around them.

This is defined in the configuration file (Example from applicationContext-hibernate.xml file)

Targets/Target Objects - The objects you want to apply an aspect, in this example to all bean names ending with Dao. In my sample project I have Dao which will do all the database related operations.

So the advice will be called on all Dao methods invocation and user login ID will be set to Oracle client identifier by our Adviser.

And we have written triggers in Oracle for insert and update operations, which will get the Client Identifier from Oracle and set to respective columns (create_dt_time, create_user_id, update_dt_time, update_user_id).



Example of my update trigger.



Conclusion

Our requirement for Auditing in this example was not business requirement and I have identified it as orthogonal feature.

After implementing this code, my business logic code is not mixed up with Auditing requirement code. There is clear separation of business and other requirements.

In this approach, my domain object do not have auditing columns, so my application there is no reference to auditing columns at all after implementing, a new developer can concentrate more on implementing business logic rather than writing or mixing up auditing code with business logic code.

Once we have written this simple code, even if new tables are added to my application, my code will not change and developer need not write code to implement the auditing feature.

This code is totally reusable and It is so less maintenance.

I'm looking forward to your feedback, questions, and comments.


Tuesday, October 24, 2006

What is IoC

Wow, what is this IoC after all……..

This is dramatization conversation between 3 people about IoC.

Layman - Srikanth, what does IoC mean to me.
Srikanth - Imagine “You are very lazy man, But you still want to eat and knows what to eat. And you wish when ever you are hungry there was some magic that will prepare and give what you want.
You do not want to prepare, maintain and clean your dishes and you can still eat what ever you want.”

Layman – wow, that’s great, I really wish something like this happen. Alright that’s all I would like to know about, Hey this is my friend JavaMan, I do not know, why this guy keeps looking for new things and keeps reading about new things, I wish he has life. I have to play golf, I would like to leave.

You both can continue.



JavaMan – Hey, what’s up. So tell me more about the IoC man.
Srikanth - IoC known as Inversion of Control (IoC) pattern, also known as Dependency Injection had been around for years but became popular recently especially with advent of Spring framework while developing light weight J2EE container.

JavaMan – Ok, can you tell me in terms of classes, what does it mean ?
Srikanth – Sure, In simple words "Do not use new() in your code for creating your Application Objects".

And Lets take an example Student and Student's Course.
Imagine Class Student has a relationship with Class Course: it wants to use the services of Class Course. The usual way to establish this relationship is to instantiate Class Course inside Class Student.

public class Student {

private Course studentCourse;

public Student() {

studentCourse = new Course();

}

}


Alternatively, if you use Spring Framework's IoC pattern, the responsibility of creating Object "studentCourse" moves from Class "Student" to the IoC framework, which creates and injects Object "studentCourse" into Object "Student ".


public class Student {

private Course studentCourse;

public Student() {

}

public setCourse(Course studentCourse) {

this.studentCourse = studentCourse;

}

}

JavaMan – Why do I have to do that, what did I gain here.
Srikanth – Imagine the changes in Course, imagine the changes in constructor for example, instead of constructor without parameter, you have constructor with parameters. You have to change you Student class again.
Imagine this change in large enterprise web application. More over you gain the control from one place the creation of all the objects.
And there are more things you can do, we will talk about those soon.
Did you get the concept of IoC ?

JavaMan – I think so, I got little bit, I think I have to get my hands dirty now with this concept. How about the famous example “HelloWorld”. Can you tell me how to write HelloWorld Example with this.

Srikanth – Sure, Ok fire up your famous editor. I have eclipse and I will use that.

Drop some of the Jars we require for this to work. (standard.jar, spring.jar, commons-logging.jar)

Create a Java Project and then create a package “com.atasisoft.project.HelloWorld”
Alright now you are ready to start the code.

First thing first, start with interface.

package com.atasisoft.project.HelloWorld;

public interface HelloWorldService {

public void sayHelloWorld();

}



Next, write the implementation class for the above interface.

package com.atasisoft.project.HelloWorld;

public class HelloWorldServiceImpl implements HelloWorldService {

public String helloWorldMessage;

public HelloWorldServiceImpl() {

}

public HelloWorldServiceImpl(String helloWorldMessage) {

this.helloWorldMessage = helloWorldMessage;

}

public String gethelloWorldMessage() {

return helloWorldMessage;

}

public void sethelloWorldMessage(String helloWorldMessage) {

this.helloWorldMessage = helloWorldMessage;

}

public void sayHelloWorld() {

System.out.println(helloWorldMessage);

}

}


Most of it is done, we have written interface and we have written class that implements interface. We just need the calling class and magic thing of IoC, which will create and maintain our Application Objects for us.

package com.atasisoft.project.HelloWorld;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.core.io.ClassPathResource;

public class HelloApp {

public static void main(String arg[]) throws Exception {

BeanFactory factory = new XmlBeanFactory(new ClassPathResource(

"hello.xml"));

HelloWorldService helloWorldService = (HelloWorldService) factory

.getBean("helloWorldService");

helloWorldService.sayHelloWorld();

}

}


Almost done, all you need the magic file(Hello.xml), keep in the classpath (Since we are using ClassPathResource to find our Hello.xml ).




All done!. If you are using Eclipse IDE the workspace will look something like this.





Run the HelloApp class and you will see your results.
Hope you got it all working.


JavaMan - So, what did we gain here.
Srikanth - good question, well with help of Spring framework we are able to manage and configure our application objects.
We are at best in Object Oriented design, our objects are loosely coupled.
This is just a start, using this building blocks and using other features like AOP on top of IoC, we can design best Enterprise Application.


Notes:-
1. All Spring Beans are Singletons.
2. The above example is setter Injection, you need to have setter method for the above example to work. Apart from setter injection, you can also use constructor Injection.
3. Autowiring - you can wire (autowire) your bean in configuration file. There are 4 types of autowiring - byName, byType, constructor, autodetect.


Next topic we will talk about is AOP.

Sunday, October 22, 2006

Spring Framework

Learn Spring Framework

Recently, I started reviewing Spring Framework and I was very impressed the way it is created.

I read about the over view and I think it is well thought framework developed and now my goal is to get as much knowledge as possible in understanding Spring Framework and applying the concepts to my new projects.

I know lots of people are already very well versed with this framework. But I would like to write this blog to give an example how I learned this framework.

I brought "Spring in Action" by Craig Walls and Ryan Breidenbach book which is best for the 1st time learners.

I will continue to post how and what I acquire my knowledge in spring framework.

I have just completed on Web Project, which involved Java Server Face (JSF) Specification and Hibernate.

Already knowing the concept of JSF and its managed bean creation feature, it helped to understand the one of the core feature of spring Inversion of control (IoC).