Monday, January 7, 2008

Dependency Injections / Inversion Of Control

In order to reduce the amount of coupling between components, most programmers follow the “Program to an interface, not an implementation” principle. Dependency injection is one such pattern that builds on top of this principle.
Dependency injection is a term used to describe a separation between the implementation of an object and the construction of an object it depends on, and the ability for a container to resolve the dependency. In turn, the client program becomes independent of the specific implementation dependency.
Lets take an example for the explanation:
Suppose, one wants to trade some FooShares. Thus, “MyTrade” depends upon the “FooShares”.
Dependency:
 public class FooShares { // some implementation }  
 public class MyTrade {  
      private FooShares foo_shares;  
      public MyTrade(FooShares foo_shares) {  
           this.foo_shares = foo_shares;  
      }  
 }  
Dependency Pull:
To get the handle to the “FooShares” somebody must create it!!!!
 public class TheCreator {  
      public void performTrade() {  
           FooShares foo_shares = <b>new FooShares()</b>;  
           MyTrade myTrade = new MyTrade(this.foo_shares);  
      }  
 }  
thus…..”MyTrade” will have to pull “FooShares” object.
Dependency Push or Injection:
 public class FooShares <b>implements Shares</b> { // some implementation }  
 public class SomeOtherShares <b>implements Shares</b> { // some other implementation }  
 public class MyTrade {  
      private Shares shares;  
      public MyTrade(<b>Shares shares</b>) {  
           this.shares = shares;  
      }  
 }  
// Both are true
MyTrade myTrade = new MyTrade(this.some_other_shares);
MyTrade myTrade = new MyTrade(this.foo_shares);
thus…..creators can now push or inject their own implementations into MyTrade. “MyTrade” no longer is dependent upon “FooShares” implementation.
Using the above principle, broadly there are three main styles of dependency injection: Constructor Injection, Setter Injection, and Interface Injection.
For more details refer following article by Martin Fowler:
http://www.martinfowler.com/articles/injection.html