The Dependency Inversion Principle (DIP) is one of the SOLID principles of object-oriented design. It promotes loose coupling between high-level and low-level modules by introducing abstractions. Here's a simple explanation with an example in Java.
Definition
High-level modules should not depend on low-level modules. Both should depend on abstractions.
Abstractions should not depend on details. Details should depend on abstractions.
Why Use DIP?
Without DIP:
- High-level classes are tightly coupled to low-level classes.
- Difficult to change or replace low-level implementations.
- Harder to test (e.g., unit testing with mocks).
With DIP:
- Use interfaces or abstract classes to depend on abstractions.
- Concrete classes implement those interfaces.
- High-level modules work with interfaces, not concrete implementations.
Java Example Without DIP (Bad)
class Keyboard {
public void input() {
System.out.println("Keyboard input");
}
}
class Computer {
private Keyboard keyboard;
public Computer() {
this.keyboard = new Keyboard(); // Tight coupling
}
public void use() {
keyboard.input();
}
}
Here, the Computer is tightly coupled to the Keyboard
.
Java Example With DIP (Good)
// Abstraction
interface InputDevice {
void input();
}
// Low-level module
class Keyboard implements InputDevice {
public void input() {
System.out.println("Keyboard input");
}
}
// High-level module
class Computer {
private InputDevice inputDevice;
public Computer(InputDevice inputDevice) {
this.inputDevice = inputDevice; // Dependency Injection
}
public void use() {
inputDevice.input();
}
}
Usage
public class Main {
public static void main(String[] args) {
InputDevice keyboard = new Keyboard();
Computer computer = new Computer(keyboard);
computer.use();
}
}
Summary
Before DIP | After DIP |
---|---|
Tight coupling | Loose coupling |
Hard to test | Easy to test |
Direct dependency | Depend on abstraction |
Difficult to extend | Easy to extend/replace |
Thanks for reading! 🎉 I'd love to know what you think about the article. Did it resonate with you? 💭 Any suggestions for improvement? I’m always open to hearing your feedback so that I can improve my posts! 👇🚀. Happy coding! 💻✨
0 comments:
Post a Comment