Java Code Geeks

Friday, December 5, 2008

Evolution from Inheritance to Composition to Dependecy Injection (Inversion of Control)

Inheritance and compositions are the most basic concepts of Object Oriented design. If there is a is-a relationship between objects, we tend to use inheritance and if there is a has-a relationship, we tend to use compositions. For example, Manager is a Employee, so Manager will be a sub-class of Employee. Otherwise, Machine has disks, so Machine object can contain many Disk objects following Composition.
It is a usual practice to follow more of Composition rather than inheriance. Reason is - composition allows loose coupling than Inheriance. In case of Inheritance, any change is super-class methods can break the client code which are using the super-class or any of its sub-classes. Whereas in case of composition, any change in the back-end class (the class that is encapsulated within another class) might not lead to changes to the client code which uses the front-end class (the class that encapsulates the back-end class).
Hence when we develop enterprise applications, we develop complex class maps where one class holds refernece of many other classes. The problem is the front end class needs to explicitely get a hold of the back-end class. For example, class A has-a Class B. In that case, we can find some code like

Class A{
private B b;
A()
{
B b = new B():
}

....

Now it becomes a problem for class A sometimes to get these references of its composite classes. Think about Class A as one EJB bean which is going to class another EJB bean B. In that case, A needs to look for B's home interface from JNDI. Or think of B's reference is available in JNDI (like B is a JDBC Datasource), in that case also A needs to look for the reference of B from JNDI.

Instead of class A, getting the reference of Class B explicitely, if some framework can inject or set the reference of class B in class A, that becomes very easy. As a result class A can concentrate on other activities. This is called "Dependency injection" (previously known as Inversion of Control). Spring framework make use of this concept very much. Even EJB 3 uses dependecny injection to inject EJB references or Persistence Contexts. Dependency injection of these frameworks can really help developers to develop cleaner code.

No comments: