Dependency Inversion Principle (DIP)

Saquib HassanSaquib Hassan
1 min read

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?

4
Subscribe to my newsletter

Read articles from Saquib Hassan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Saquib Hassan
Saquib Hassan

I am an enthusiastic novice in the world of programming, seeking to acquire knowledge and expertise in this field. I am driven by a passion for technology and a desire to master the tools and techniques that will help me succeed in my career.