Wednesday, March 20, 2013

DEPENDENCY INJECTION (DI)

What I feel is people understand Dependency Injection (DI) more than Inversion of Control (IoC). When I ask in an interview, “What have you used spring for?”. The answer normally is, “I have used it for IoC” or “I have used it for DI”. But when I ask the difference between IoC and DI, I mostly  get the answer, “They are the same” or “DI was earlier called IoC”.
What really is DI? Is it the really new name for IoC? Is there any difference between DI and IoC? Lets try and explore there questions.
Let me begin by stating that DI is not the new name of IoC. DI is something which affirms to IoC concept. When we do DI, we are doing IoC (Not the other way round). Following IoC does not mean DI would have happened. DI is just one of the ways to achieve IoC.
Example: God creating Man
When God creates Man. He would start with an Empty Body (Body Class). Then he would create new Hands, new Legs, new Face inside the Body (inside Body constructor). This Body now has to live with whatever Hands, Legs, Face were created (Tightly coupled). But no one can refute that a Man is created alright.
Now if God wants to create another Man (He would need to do so a lot, given there are 6 billion of us on this planet, and we are born regularly), God will start with another empty Body and try and put different features to it. Say SmallHands, RoundFace, LongLegs.
So now God will keep on creating new Bodies (class Body1, class Body2, class Body3) etc. Poor God!
How nice it would have been, had God just created one Body (written one Body class) and said that it will have SomeHands, SomeFace and SomeLegs.
How nice it would have been had God had a helper (Framework like Spring), who would create different Hands (SmallHands, LongHands), different Faces (RoundFace, SquareFace). He would just copy the generic Body God created and will insert these Hands/Legs/Face to it independently. Good for God!
This is called Dependency Injection, where dependencies (on which Body depends) are not created (inside constructor) when Body is created by God. They are instead created and fitted when Body needs to be sent to Earth.
This affirms to IoC as control of creating new Type of Hands/Face/Legs lie not with the God but with the Helper who makes job of God easier,
This is what they call “Don’t call us, We’ll call you” (Hollywood Principle). Body, please dont call Hands() constructor to create new Hands, instead when Helper needs a Body() to be sent to Earth,  it will create new Hands(), will then call Body and inject the Hands.

No comments:

Post a Comment