Dependency Inversion Principle (DIP)

Dependency Inversion Principle (DIP)

The Dependency Inversion Principle (DIP) in software design advocates high-level modules should not depend on low-level details, but both should rely on abstractions.

First, we have an IWeapon interface:

interface IWeapon {
   void Fire();
}

Then some Weapons implementing it:

class Mjolnir : IWeapon {
  public void Fire() {
    Console.WriteLine("Lightening strike");  
  }
}

class Shield : IWeapon {
  public void Fire() {
    Console.WriteLine("Shield defense");  
  }
}

Next our Hero comes Captain America:

class CaptainAmerica {

  private IWeapon _weapon;  

  public CaptainAmerica(IWeapon weapon) {
    _weapon = weapon;
  }

  public void EngageInBattle() {
   _weapon.Fire(); 
  }
}

And finally we inject a concrete Weapon:

CaptainAmerica mjolnir = new CaptainAmerica(new Mjolnir());
mjolnir.EngageInBattle(); // Uses Mjolnir -> Lightening strike

//Suppose, Thanos is coming full forces -> What'll Cap do now?!
//He uses his shield
//He's not fully dependent on Mjolnir

CaptainAmerica shield = new CaptainAmerica(new Shield());
shield.EngageInBattle(); // Uses Shield -> To defend himself

So in summary:

  1. CaptainAmerica doesn't depend directly on Mjolnir or Shield

  2. CaptainAmerica depends on abstraction IWeapon

  3. The actual weapon is injected through constructor

  4. This allows CaptainAmerica to work with any class that implements IWeapon without being tightly coupled to specific weapon implementations.

And to me, this is dependency inversion principle. Though this does put a smile on Thanos's face I'm sure. How about you?