Disclaimer

The views expressed on this blog are my own and do not necessarily reflect the views of Oracle.

Thursday, May 22, 2008

Inversion of Control

In layman terms "Instead of having dependencies to the enclosing environment, let environment decide on how to react on enclosed program’s actions or events"... The popular phrase is "Don’t call me, I will call you"

Implementation using structured programming languages w/o following the Inversion of Control (IoC) design pattern are fairly simple but had a tight coupling. So, in long run becomes difficult to maintain and thus involves huge investments and overheads...

To understand it better. Say there is an object Car and an object Engine. An user class may implement it as:
Class Engine{...}

Class Car{
private Engine e;
Car(){
e= new Engine();
}
}


The prbolem with the above code is the tight coupling between the engine and the car classes. Say if way to construct an engine object changes then it will require the Car class to be modifed. Now, if we change the code for class Car as:
Class Car{
private Engine e;

Car(Engine e){
this.e = e;
}
}


Now, in this case class Car doesn't need to know that how to create engine object. Invoker of class Car has the responsibility to pass the proper engine instance to class car. This way the control is inverted and is driven by environment that makes the user program much more flexible and loosely coupled...

Spring is one of the popular J2EE framework, which is having an Inversion of Control Container as a very important component (sub-framework). Spring framework heavily uses this principal and thus moves the event or flow management to the framework from the application code. It uses a flavor of IoC called Dependency Injection.

Where, IoC increases tremendous flexibility to the application, it also injects the complexity to the system and makes it pretty less deterministic...

To be continued....

1 comment:

Anonymous said...

I'm not sure 'Inversion of control' qualifies as a component/framework.

It might be more accurate to say that the spring framework 'implements' the 'Inversion of Control Pattern' to a great degree.

The key idea being that its an Object Oriented design pattern rather than a component or framework in itself..

:)