DEV Community

Upendra-Allagadda
Upendra-Allagadda

Posted on

Dependency Injection

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.
Image description

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay