Holy cows! "Dependency Injection" sounds like an action movie, like the second part of "Independency Day! yeah!!!....(don't get too excited -__- , it isn't)
When I started programming in Java everything was happiness, everything was beautiful and nothing hurt. You code, you run it, it works, you love it......but, (there is always a but) one day I was asked to work with "Dependency Injection ", so I gave it a try. Have to be honest, I got super confused. The whole idea about "injecting" something scared me (just kidding =) ) Well, the point is that, at the beginning, it was hard to totally understand this concept. It was like I knew what to do and how to make it work, but didn't really understand how and why.
However, one day, my best friend google spoke and showed me the truth!
I want to share an interesting article I found with a nice example. This helped me to understand what Dependency Injection is and why we need it. Enjoy!
------------
Understanding Dependency Injection and its Importance, A tutorial
Any application is composed of many objects that collaborate with each other to perform some useful stuff. Traditionally each object is responsible for obtaining its own references to the dependent objects (dependencies) it collaborate with. This leads to highly coupled classes and hard-to-test code.
For example, consider a
Car
object.A
Car
depends on wheels, engine, fuel, battery, etc. to run. Traditionally we define the brand of such dependent objects along with the definition of the Car
object.Without Dependency Injection (DI):
class Car{
private Wheel wh= new NepaliRubberWheel();
private Battery bt= new ExcideBattery();
//The rest
}
Here, the
Car
object is responsible for creating the dependent objects.What if we want to change the type of its dependent object - say
Wheel
- after the initial NepaliRubberWheel()
punctures? We need to recreate the Car object with its new dependency say ChineseRubberWheel()
, but only the Car
manufacturer can do that.Then what does the
Dependency Injection
do us for...?When using dependency injection, objects are given their dependencies at run time rather than compile time (car manufacturing time). So that we can now change the
Wheel
whenever we want. Here, the dependency
(wheel
) can be injected into Car
at run time.After using dependency injection:
class Car{
private Wheel wh= [Inject an Instance of Wheel at runtime]
private Battery bt= [Inject an Instance of Battery at runtime]
Car(Wheel wh,Battery bt) {
this.wh = wh;
this.bt = bt;
}
//Or we can have setters
void setWheel(Wheel wh) {
this.wh = wh;
}
}
Source: Understanding dependency injection
No comments:
Post a Comment