Inversion Of Control and Dependecy Injection.

Inversion of Control (IoC) is important pattern when we use frameworks to develop web development. Mainly Spring framework using IoC pattern explicitly and core of Spring framework mainly built on IoC for application context, bean factory. 

IoC is simply pushing configuration, objects, and other required resource to a class rather than class pulling all information to run flow.  This is very simple definition of IoC. When I started Spring framework for projects almost 3 years ago, First I confused with IoC and Dependency Injection. So many articles and books try to add more confusion. Until I read the Java development with the Spring Framework by Rod Johnson, Juergen Hoeller, Alef Arendsen, Thomas Risberg, and Colin Samplaeanu

Dependency Injection is a flavor of IoC. Spring using dependency injection to achieve IoC. Lets see a example, how to improve a code by using IoC.

Here is a simple class to construct a car.
public class Car {
   public void buildCar() {
       CarBody cBody = new CarBody("SUV");
        Engine engine = new Engine("honda");
        this.constructCar(cBoby, engine);
   }
}

After execution of buildCar method, we have a car object with SUV body, honda engine. Ok. All are good and now we need to construct GM car. We need to directly touch buildCar method to recreate it. Since car is a generic object, it is prone to constant changes. It is pain to change time buildCar method to create different cars. If you are asked to improve the above code, instantly we change buildCar method signature to parameterize body, engine, tire like

buildCar(CarBody body, Engine engine);

Thats starting of IoC pattern. The parameterize version of buildCar would solve almost all issues programmatically. But we can't customize a container or framework to call this parameterize buildCar method. We want to do one more level of externalizing. 

Dependency Injection can be done based on constructor, setter methods and interface. But most of developers preferred to use setter methods. So we are going to add all setter methods for engine, body and tire.

public void setBody(String body)
public void setEngine(String engine)

Now our Car class exposed it's important components to others including a container mainly we can call this setters from a configuration files. Thats exactly the goal of IoC.

Comments

Popular posts from this blog

Coupon Crazy

Google's Killer Application.

Uncontrolled Musing