💡 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
🌟 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!
- Golang Dependency Injection - Just in 5 Minutes!
- Interface Segregation Principle (ISP) Explained in 100 Seconds
- You Aren’t Gonna Need It Principle (YAGNI) Explained in 100 Seconds
- Liskov Substitution Principle (LSP) Explained in 100 Seconds
- KISS Design Principle Explained in 100 Seconds
- DRY Principle Explained in 100 Seconds
- "Tell, Don't Ask" Principle Explained in 100 Seconds
Follow me to stay updated with my future posts:
Top comments (0)