DEV Community

Luke Babich
Luke Babich

Posted on

Dependency Injection in under 2minutes

Hello Devs! Lets talk DI or dependency injection.

The easy to digest analogy:

You work in a car factory. Each part of the car making process requires either multiple pieces of specialized machinery or a person to put the car together.

Stage 1 of production requires a machine that cuts the frame, and another to lift the frame to stage 2.

In stage 2 it then puts assembles the frame the car puts it together. It then uses the same machine to lift and take it to stage 3.

In stage 3 we may have a person who comes and inspects the final product and then sends it on its way.

The summary:

The above analogy can be thought of as you have a code base or group of functionality (the car factory) that is made up of different services or functionality (machines or people).

These pieces of functionality could be used in one or multiple places in your code base (the stages of production).

Dependency injection is about providing your functionality to your different pieces of code. Without that code directly importing or using that piece of code (this is the responsibility of something called an injector to provide it).

This makes it easy to swap it out and only have to make sure that whatever you are swapping it with conforms to the interface that piece of code requires (it is about making sure the contract of functionality is met).

The benefit of dependency injection is:

  1. Decreased coupling between pieces of code
  2. Increased flexibility in swapping functionality (what happens if you need a new machine to lift or move assemble the car?)
  3. Ease of testability of your code
  4. Less boilerplate
  5. It allows concurrent development. Multiple developers can work on different classes that use each other, while only needing to know the interface the classes will communicate through.

I hope this has helped!

Top comments (0)