Dependency Injection

Dependency Injection

Oh those Angular days....

When I first began working as a Front End Engineer for a Nashville based company I was onboarded in an very interesting Angular ( Front End Framework) Project. I had very little experience at the time and encountered a concept called Dependency Injection. I had no idea what it meant, and like every new concept in the software business it's easy to get impostor syndrome.

As a matter of fact, dependency injection is a very simple concept and by the end of this post you will know what it is and why it's relevant.

What is it?

It's a programming technique that makes classes independent of its dependencies.

Why its important?

  • Reusability.

  • It decouples the usage of an object from its creation.

  • Reduces chances of changing a class if one of its dependencies change.

  • Better for testing and debugging.

How is it implemented?

class Wheel {}

class Bike{
  wheel;
  constructor(){
     this.wheel = new Wheel();
  }
}

In the previous code the Bike class needs to be passed a wheel in order to instantiate properly. But what if the Wheel class changes and now needs to be passed another object? Or some of the specifics of how its instantiated or used also change? You would also have to go in and change the Bike class in order to account for such changes. Dependency Injection accomplishes this as shown in the following snippet.

class Bike{
  constructor(wheel: Wheel){}
}

By moving the instantiation out of the consumer class changes to Wheel are decoupled from Bike and will prevent code breaks, even better it will prevent you from having to chase around the code for any objects that may depend on Wheel .

The consumer class (Bike), has not idea about the creation of the Wheel object, this is the task of the dependency injection framework set in place. A

We can also think of it by using the battery and car analogy. Imagine having to use a battery that only works for a specific vehicle, not very convenient right? Wouldn't it be better to decouple the battery from the car and manufacturing it (programming it) to a standard? (interface) such that it can be reused in other vehicles for example.

From Angular documentation:

image.png

Up Next... container (Service Locator) pattern.