Dependency Injection an attempt to explain

Dependency Injection an attempt to explain

I was explaining to a friend the other day what dependency injection was, and even though I use this in almost every class I create I could not come up with a simple analogy. There is a rule that I use sometimes that my father taught me: “Will your mother understand?”. This is not to say my mother is stupid (she is not) it’s just that she is not tech savvy. If I can explain dependency injection so she will understand, then anyone can understand it. Here is my attempt.

Dependency injection is like hanging a LCD screen instead of a painting in your living room. You can display anything on a LCD including the painting.

In technical terms you supply your class with its dependencies. This is mainly done by passing them through the constructor (Constructor Injection), but you can also do this in other ways such as property injection. Your dependences will implement some sort of contract such as an abstract class or an interface. This enables your class to interact with it. You pass a concrete implementation of the contract in through the constructor and then the implementations details can be invoked by the class. It’s worth noting that in the world of dynamic languages its different and you don’t have to implement contracts just have the method there.

In our example the LCD is our contract and the painting is the concrete implementation.

public interface ILcd
{
  void Show();
}
public class Painting : ILcd
{
  public void Show()
  {
    //Display Painting
  }
}
public class LivingRoom
{
  private ILcd lcd;
  public LivingRoom(ILcd lcd)
  {
    this.lcd = lcd;
  }
 
  public void EnterRoom()
  {
    lcd.Show();
  }
}

And when you want to change the painting to display video, you would just create a new implementation and inject that.

public class Video : ILcd
{
  public void Show()
  {
    //Display Video
  }
}

Bringing it all together:

public class House
{
  public LivingRoom livingRoom;

  public void LivingRoom ()
  {
    ILcd lcd = new Video();
    livingRoom = new LivingRoom(lcd);
    livingRoom.EnterRoom();
  }
}

There is much more to all of this including dependency injection containers which I might cover in later posts. I hope you find this as useful as I have writing it.