What you will learn
- Each of the five SOLID principles in plain language.
- How they show up in one realistic checkout example.
- How to spot violations in code reviews and interviews.
The five principles
| Letter | Principle | One-liner |
|---|---|---|
| S | Single Responsibility | A class should have one reason to change. |
| O | Open/Closed | Add behaviour by adding code, not editing working code. |
| L | Liskov Substitution | Subtypes must work wherever the parent type is expected. |
| I | Interface Segregation | Don’t force clients to depend on methods they don’t use. |
| D | Dependency Inversion | High-level logic depends on abstractions, not concrete details. |
The “before” picture
A typical first draft:
class Checkout:
def checkout(self, customer, items, discount_type):
subtotal = sum(i.price * i.qty for i in items)
if discount_type == "percent10":
subtotal *= 0.9
elif discount_type == "flat300":
subtotal -= 300 if subtotal >= 2000 else 0
# ... a new elif for every promotion
smtp = SmtpClient("smtp.example.com")
smtp.send(customer, f"Order confirmed: {subtotal}")
return subtotal
Problems: pricing, discounts and email are tangled in one method (S); every new promotion edits this method (O); swapping email for SMS, or testing without a mail server, requires editing it (D).
The “after” picture
"""SOLID in practice: an order checkout refactored step by step."""
from abc import ABC, abstractmethod
from dataclasses import dataclass
# --- O: open for extension, closed for modification -------------------------
class DiscountPolicy(ABC):
@abstractmethod
def discount(self, subtotal: float) -> float: ...
class NoDiscount(DiscountPolicy):
def discount(self, subtotal):
return 0.0
class PercentOff(DiscountPolicy):
def __init__(self, percent: float):
self.percent = percent
def discount(self, subtotal):
return subtotal * self.percent / 100
class FlatOffAbove(DiscountPolicy):
def __init__(self, threshold: float, amount: float):
self.threshold, self.amount = threshold, amount
def discount(self, subtotal):
return self.amount if subtotal >= self.threshold else 0.0
# --- D: depend on abstractions, not concrete senders --------------------------
class Notifier(ABC):
@abstractmethod
def send(self, to: str, message: str) -> None: ...
class EmailNotifier(Notifier):
def send(self, to, message):
print(f"[email to {to}] {message}")
class SmsNotifier(Notifier):
def send(self, to, message):
print(f"[sms to {to}] {message}")
# --- S: each class has one reason to change ------------------------------------
@dataclass
class LineItem:
name: str
price: float
qty: int
class PriceCalculator:
def __init__(self, policy: DiscountPolicy):
self.policy = policy
def total(self, items: list[LineItem]) -> float:
subtotal = sum(i.price * i.qty for i in items)
return round(subtotal - self.policy.discount(subtotal), 2)
class CheckoutService:
"""Coordinates; doesn't know how prices are computed or how messages are sent."""
def __init__(self, calculator: PriceCalculator, notifier: Notifier):
self.calculator, self.notifier = calculator, notifier
def checkout(self, customer: str, items: list[LineItem]) -> float:
amount = self.calculator.total(items)
self.notifier.send(customer, f"Order confirmed: Rs {amount:.2f}")
return amount
if __name__ == "__main__":
cart = [LineItem("keyboard", 1500, 1), LineItem("mouse", 500, 2)]
for policy, notifier in [(NoDiscount(), EmailNotifier()),
(PercentOff(10), SmsNotifier()),
(FlatOffAbove(2000, 300), EmailNotifier())]:
CheckoutService(PriceCalculator(policy), notifier).checkout("asha", cart)
[email to asha] Order confirmed: Rs 2500.00
[sms to asha] Order confirmed: Rs 2250.00
[email to asha] Order confirmed: Rs 2200.00
How each principle shows up:
- S:
PriceCalculatorcomputes totals;CheckoutServicecoordinates; notifiers send messages. Changing the message channel never touches pricing. - O: a new promotion is a new
DiscountPolicysubclass.PriceCalculatorstays untouched. - L: any
DiscountPolicycan replace another; each returns a sensible discount and never raises for valid input. A subclass that, say, returned a negative discount or required extra setup calls would break substitutability. - I:
Notifierhas justsend(). If we had oneCommunicatorinterface withsend_email,send_sms,send_push, every implementation would have to stub methods it can’t support. - D:
CheckoutServicereceives aNotifierandPriceCalculatorthrough its constructor (dependency injection). Tests can pass a fake notifier that records messages.
Liskov, the classic trap
Square extends Rectangle looks natural, but if Rectangle lets you set width and height independently, a Square must either break that contract or behave surprisingly:
def stretch(r):
r.width = 4
r.height = 5
assert r.area() == 20 # fails for a Square that keeps sides equal
The fix is to not make Square a subtype of a mutable Rectangle (use a common Shape interface instead). Liskov is about behavioural compatibility, not just matching method names.
Spotting violations
- Long
if/elifchains on a type or mode → Open/Closed (use polymorphism/strategy). new SmtpClient()deep inside business logic → Dependency Inversion (inject it).- Methods that raise
NotImplementedErrorin some subclasses → Liskov or Interface Segregation. - A class whose name ends in “Manager” with 30 methods → Single Responsibility.
SOLID is a guide, not a law: a 30-line script doesn’t need five interfaces.
Key takeaways
- S: one reason to change per class. O: extend by adding classes. L: subtypes must honour the parent’s behaviour. I: small, focused interfaces. D: inject abstractions.
- Strategy-style interfaces plus constructor injection deliver most of SOLID’s benefit.
- Watch for type switches, hard-coded dependencies and stubbed methods.
Exercises
- Add a
BuyXGetYFreediscount policy without changing any existing class. - Write a
FakeNotifierthat stores messages in a list, and a test asserting the checkout message. - Refactor a “Printer” interface with
print,scanandfaxso a basic printer doesn’t have to implement fax.
Quiz
- Which principle does a growing
if discount_type == ...chain violate? - Why is
Square extends Rectanglea Liskov problem? - What does dependency injection make easier?
Show answers
- Open/Closed: every new discount requires modifying existing, working code.
- Code that relies on setting width and height independently breaks when given a Square, so a Square can’t safely substitute for a Rectangle.
- Swapping implementations (email vs SMS) and testing with fakes, because the class no longer constructs its own dependencies.