π‘ 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)