Lesson 3 of 12 Foundations

SOLID Principles with Examples

SOLID principles with one runnable Python example: single responsibility, open/closed, Liskov, interface segregation and dependency inversion.

40-50 min beginner 0/12 lessons done
Course contents Lesson 3 of 12 · 0 done
On this page (9 sections)
  1. What you will learn
  2. The five principles
  3. The “before” picture
  4. The “after” picture
  5. Liskov, the classic trap
  6. Spotting violations
  7. Key takeaways
  8. Exercises
  9. Quiz

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

LetterPrincipleOne-liner
SSingle ResponsibilityA class should have one reason to change.
OOpen/ClosedAdd behaviour by adding code, not editing working code.
LLiskov SubstitutionSubtypes must work wherever the parent type is expected.
IInterface SegregationDon’t force clients to depend on methods they don’t use.
DDependency InversionHigh-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: PriceCalculator computes totals; CheckoutService coordinates; notifiers send messages. Changing the message channel never touches pricing.
  • O: a new promotion is a new DiscountPolicy subclass. PriceCalculator stays untouched.
  • L: any DiscountPolicy can 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: Notifier has just send(). If we had one Communicator interface with send_email, send_sms, send_push, every implementation would have to stub methods it can’t support.
  • D: CheckoutService receives a Notifier and PriceCalculator through 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/elif chains on a type or mode → Open/Closed (use polymorphism/strategy).
  • new SmtpClient() deep inside business logic → Dependency Inversion (inject it).
  • Methods that raise NotImplementedError in 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

  1. Add a BuyXGetYFree discount policy without changing any existing class.
  2. Write a FakeNotifier that stores messages in a list, and a test asserting the checkout message.
  3. Refactor a “Printer” interface with print, scan and fax so a basic printer doesn’t have to implement fax.

Quiz

  1. Which principle does a growing if discount_type == ... chain violate?
  2. Why is Square extends Rectangle a Liskov problem?
  3. What does dependency injection make easier?
Show answers
  1. Open/Closed: every new discount requires modifying existing, working code.
  2. Code that relies on setting width and height independently breaks when given a Square, so a Square can’t safely substitute for a Rectangle.
  3. Swapping implementations (email vs SMS) and testing with fakes, because the class no longer constructs its own dependencies.

Finished this lesson?

Mark it complete to track your progress (saved in this browser).