SOLID Principles Gone Wrong
This post helps you spot bad software patterns—specifically, violations of the SOLID principles in Python code.
S — Single Responsibility Principle
One class should do one thing, and do it well.
class Report:
def generate(self):
return "Report content"
def save_to_file(self, filename):
with open(filename, 'w') as f:
f.write(self.generate())
O — Open/Closed Principle
Software should be extendable, not modifiable, for new behavior.
class DiscountCalculator:
def calculate(self, customer_type, total):
if customer_type == "Regular":
return total * 0.9
elif customer_type == "VIP":
return total * 0.8
L — Liskov Substitution Principle
Subtypes must be substitutable without breaking the program.
class Bird:
def fly(self):
print("Flying high!")
class Ostrich(Bird):
def fly(self):
raise Exception("Ostriches can't fly!")
I — Interface Segregation Principle
Don't force classes to implement unused methods or interfaces.
class Worker:
def work(self):
pass
def eat(self):
pass
class Robot(Worker):
def work(self):
print("Robot working")
def eat(self):
pass # makes no sense for a robot
D — Dependency Inversion Principle
Depend on abstractions, not on concrete implementations.
class LightBulb:
def turn_on(self):
print("Bulb on")
def turn_off(self):
print("Bulb off")
class Switch:
def __init__(self, bulb: LightBulb):
self.bulb = bulb
def operate(self):
self.bulb.turn_on()
No comments:
Post a Comment