Skip to content

Instantly share code, notes, and snippets.

@Drblessing
Created June 7, 2023 20:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Drblessing/6448819627d2eb50ee33808805c6a0df to your computer and use it in GitHub Desktop.
Save Drblessing/6448819627d2eb50ee33808805c6a0df to your computer and use it in GitHub Desktop.
The Dependency Inversion Principle: High level modules should not depend on low level modules.
# Dependency Inverson Principle
# High level modules should not depend on low level modules
# Without Dependency Inversion:
class LightBulb_wo:
def turn_on(self):
print("LightBulb: turned on...")
def turn_off(self):
print("LightBulb: turned off...")
class ElectricPowerSwitch_wo:
def __init__(self, l: LightBulb_wo):
self.lightbulb = l
self.on = False
def press(self):
if self.on:
self.lightbulb.turn_off()
self.on = False
else:
self.lightbulb.turn_on()
self.on = True
lightBulb = LightBulb_wo()
switch = ElectricPowerSwitch_wo(lightBulb)
switch.press()
switch.press()
# ElectricPowerSwitch depends on LightBulb
# What if we want to add a fan?
# With Dependency Inversion:
from abc import ABC, abstractmethod
class Switchable(ABC):
@abstractmethod
def turn_on(self):
pass
@abstractmethod
def turn_off(self):
pass
class LightBulb(Switchable):
def turn_on(self):
print("LightBulb: turned on...")
def turn_off(self):
print("LightBulb: turned off...")
class Fan(Switchable):
def turn_on(self):
print("Fan: turned on...")
def turn_off(self):
print("Fan: turned off...")
class ElectricPowerSwitch:
def __init__(self, c: Switchable):
self.client = c
self.on = False
def press(self):
if self.on:
self.client.turn_off()
self.on = False
else:
self.client.turn_on()
self.on = True
lightBulb = LightBulb()
switch = ElectricPowerSwitch(lightBulb)
switch.press()
switch.press()
fan = Fan()
switch1 = ElectricPowerSwitch(fan)
switch1.press()
switch1.press()
# The key idea of the Dependency Inversion Principle is to depend upon abstractions, not concretions.
# In our example, ElectricPowerSwitch (the high-level module) doesn't depend on LightBulb or Fan (the low-level modules). Instead, it depends on the Switchable interface. This allows us to add new Switchable objects without having to modify ElectricPowerSwitch at all. If we didn't have the Switchable interface and wanted to add a new device that can be switched on and off, we would have to modify ElectricPowerSwitch which would violate the Open/Closed principle.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment