DEV Community

Cover image for Dependency Inversion Principle (DIP) Explained in 100 Seconds
Dzung Nguyen
Dzung Nguyen

Posted on β€’ Edited on

1

Dependency Inversion Principle (DIP) Explained in 100 Seconds

πŸ’‘ What is Dependency Inversion Principle (DIP)?

πŸ’‘ The DIP, part of the SOLID principles, states that:

"High-level modules should not depend on low-level modules. Both should depend on abstractions."

🎯 Example

Imagine you’re plugging in a lamp at home. You don’t need to worry about who made the power outlet or the lamp; all you care about is that the outlet provides electricity, and the lamp can use it.

The power outlet is an abstraction β€” it doesn’t depend on the lamp, and the lamp doesn’t depend on the specific outlet. This way, you can plug in any device, like a phone charger or a TV, and it will work as long as it fits the standard outlet.

Code Example

DIP 1

DIP 2

🌟 Benefits

βœ… Flexible Code: You can easily swap out classes.
βœ… Easier Testing: Mock or replace the low-level details during testing.
βœ… Cleaner Design: High-level logic focuses on what to do, not how to do it.

⚠️ Signs of DIP Violations

❌ High-level modules directly depend on low-level modules.
❌ No interfaces or abstractions; classes rely on concrete implementations
❌ Code is hard to test because real implementations can't be easily mocked.
❌ Changes to one part of the system break other parts due to tight coupling.
❌ Extending or swapping components requires major code modifications.

βœ… Applying DIP

The DIP suggests using abstractions (interfaces/ abstract classes) instead of directly depending on concrete implementations.

  • High-level code (the "big picture" logic) depends on interfaces.
  • Low-level code (the "details") implements those interfaces.

πŸ“° Others

Interested? πŸ˜ƒ Check out other posts from my programming principles series!


Follow me to stay updated with my future posts:

Top comments (0)

Visualizing Promises and Async/Await πŸ€“

async await

☝️ Check out this all-time classic DEV post on visualizing Promises and Async/Await πŸ€“