Object Oriented Design: Dependency Inversion Principle (DIP)
The Dependency Inversion Principle (DIP) is one of the SOLID principles of object-oriented design and it emphasizes the importance of decoupling in software architecture.
Dependency Inversion Principle states that:
- 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.
Let’s illustrate with an example:
Without Dependency Inversion:
Imagine you have a light bulb class and a switch to operate it.
class LightBulb {
void turnOn() {
System.out.println("LightBulb: Bulb turned on...");
}
void turnOff() {
System.out.println("LightBulb: Bulb turned off...");
}
}
class Switch {
private LightBulb lightBulb;
public Switch(LightBulb lightBulb) {
this.lightBulb = lightBulb;
}
void operate() {
// some logic to turn on or turn off
}
}
In the above code, Switch
class directly depends on the LightBulb
class. If we were to introduce another device, like a fan, the Switch
class would need changes, making it less flexible and violating the open/closed principle.
With Dependency Inversion:
We introduce an interface (Switchable
) that both the high-level module (Switch
) and the low-level modules (LightBulb
, Fan
) depend upon.
interface Switchable {
void turnOn();
void turnOff();
}
class LightBulb implements Switchable {
@Override
public void turnOn() {
System.out.println("LightBulb: Bulb turned on...");
}
@Override
public void turnOff() {
System.out.println("LightBulb: Bulb turned off...");
}
}
class Fan implements Switchable {
@Override
public void turnOn() {
System.out.println("Fan: Fan turned on...");
}
@Override
public void turnOff() {
System.out.println("Fan: Fan turned off...");
}
}
class Switch {
private Switchable device;
public Switch(Switchable device) {
this.device = device;
}
void operate() {
// some logic to turn on or turn off
}
}
With this revised design:
Switch
doesn't directly depend onLightBulb
orFan
. It depends on theSwitchable
abstraction, making it decoupled from the specific devices.- Introducing new devices or changing existing devices has minimal impact on the
Switch
class. - The high-level
Switch
module and low-level modules (LightBulb
,Fan
) both depend on theSwitchable
abstraction, adhering to the Dependency Inversion Principle.
This approach makes the system more flexible, extensible, and easier to maintain.
Further Learning at DSAGuide.com
For an in-depth exploration of data structures, algorithms, and coding interview solutions, I invite you to visit DSAGuide.com. Elevate your understanding with our detailed guides on essential data structures, algorithms and coding interview problem solving.