Dependency injection may sound like a very complicated term but the actual meaning is as simple as passing an object/function to the dependent object/function.
In fact many of us might have used dependency injection without knowing what it is actually called.
Some examples of dependency injection are passing required objects as parameter to a constructor or function.
Why actually do we need dependency injection?
Quite often, when we develop something, one class might be dependent on other. It might look simple to handle this at this point of time. But as the design grows, we will end up with so many classes dependent on so many other classes. This increases so much coupling between classes. In future if you decide to change one class then you need to change some parts of code in dependent classes as well. This is time consuming process and can take lot of effort. So here instead of creating object every time we will inject the object whenever required. It decouples one class from other.
The other way Dependency injection is useful is, it allows developers to write unit test cases easily.
Eg: You can write unit tests to the functions by sending already created objects as parameter.
Moreover, It is used in IOC (Inversion of control) design principle which I will be posting about it later.
Top comments (0)