Understanding about Dependency Injection

Searching on Google, you can see that: there are a lot of tutorials about Dependency Injection, each one with a different style. Perhaps, some of you can perceive it quickly, someone is not. So, I would like to summarize again and try to write about it in an easy way to understand. (I will try my best 😀 ).

The main idea of Dependency Injection is: you don’t depend on anyone and no one depends on you. I will call you when I need and you too.

Let me talk more specifically about it!

Someday in the past, I usually wrote my code like the below:

Assume, you have an object Circle, this object has a method named draw() as below:

Now, I want to use this object to draw a circle, I will initialize the object Circle within the constructor and I will write the code as below:

Obviously, you see my object, Drawing, is depending on your object Circle (that means I am depending on you), because every time I run the application, the object Drawing must keep the information of the object Circle. This is the first drawback of this code.

The second drawback is that if in the future, I want to draw a triangle, I must declare again another object to satisfy my needs. This is cause the object Drawing will constantly change according to the needs.

So, how can we resolve this drawback?

The second drawback can resolve by using the interface. Your object Circle will implement an interface named Shape, details as below:

In the future, if I want to draw a triangle, I only need to create a new class and implement the interface Shape.

For the first drawback, Dependency Injection will resolve it.

Let’s see how Dependency Injection can resolve this problem, I will modify the object Drawing as below:

As you can see, if I only need my object Drawing to prepare the tool to draw, I don’t need to call your object Circle, code will be:

After preparing complete, I will need you to draw a circle, I will call you:

Actually, maybe you already worked on the code but you didn’t know that this is Dependency Injection.

Add Comment