Solly
Lesson

01 Foundations: SOLID and ESCOAT

01 Foundations: SOLID and ESCOAT

Before your first LLD exercise: a beginner's map

You need basic Python functions, classes, dictionaries and loops. You do not need to know SOLID, design patterns, concurrency or the words used in this course yet. Low-level design (LLD) means deciding which pieces of a program hold data, which pieces perform each job, and how they talk to each other so the program still works when requirements change.

Try this order for every exercise:

  1. Read Requirements: In your own words, write down the job the program must perform. In the first order example: validate an order, ask a price calculator for the total, save it, send a notice and return the total.
  2. Read E: Expected execution: This is an example of how somebody else will call your code. The missing PlaceOrder(...).place(order) is your task to create; the Validator, Repo and Notify examples are collaborators supplied by the caller. The exact names, inputs, outputs and error behavior in the example are the contract the tests expect. You do not paste the whole example into src/solution.py.
  3. Open src/solution.py: Edit this learner file. Read tests/test_functional.py to see normal behavior and tests/test_design_stress.py to see what change the design must survive. Keep test files unchanged. A test's assert says what must be true; it does not tell you how to build the solution.
  4. Use Test to check your work: The Test task runs both the ordinary and change-pressure tests. The Run task executes the supplied ordinary acceptance example against your code; Test also checks the design-stress scenarios. Passing Run is a useful first check, not proof that your design survives future changes. If an assertion fails, check its expected value, the input and your code's actual output or call order.
  5. Explain your choice before hints: Ask: What must always work? What could change later? Who owns each piece of state? Would another class or interface genuinely help? What happens first, next and on failure? Write a few sentences or sketch arrows; no formal diagram is required.
  6. Reveal help gradually: Hints may show a question, a partial code change or a plain-language explanation without any edit. Preview a suggested patch; don't replace working code blindly. The final hint is an optional complete solution, not a step you must apply to finish.
  7. Answer the SCOAT quiz: It asks five reasoning questions about the exercise you just attempted. Use the feedback to explain why an option is right, not just memorize its letter.

A tiny example of the interface contract:

class Double:
    def run(self, number):
        return number * 2

assert Double().run(3) == 6

The caller expects a class named Double, a method named run, one input and a return value of six. You may choose how to implement it, but you cannot silently rename run or return a printed message instead of the number.

The five practical questions (SCOAT) in everyday language:

  • S — Stable roles: What job will always be needed? A pricing component calculates a total; it doesn't also send email.
  • C — Change: What part might vary? An ordinary price rule could later become a campaign rule.
  • O — Ownership: Who has the data, and who is allowed to change it? One order workflow controls when saved and notified state changes.
  • A — Abstraction need: Do we need a replaceable component? Use a direct function when nothing varies; add a boundary only for a real need.
  • T — Topology: In what order do calls happen? validate → price → save → notify. If validation fails, later steps must not run.

SOLID is a later audit: it asks whether each component has a coherent job, changes can be extended safely, replacements keep their promises, callers depend only on required capabilities and high-level decisions avoid concrete infrastructure dependencies. You can learn each principle from the examples below; don't try to memorize all ten headings before solving your first task.

Historical naming note: Some folders retain older SCALE names for compatibility. Their lessons still support the current SCOAT questions: stable role (S), change (C), arrangement/abstraction (A), link interactions/topology (T) and establish lifetime/ownership (O). They are not a second process to memorize.

After you pass: Explain why your code still works when the stress test replaces a collaborator or changes state. Try predicting one thing that would break a simpler but brittle implementation. Being able to explain that trade-off matters more than an extra interface.

Your next step: Open the 01 SRP exercise now. You do not have to master the many advanced reference examples below before starting. Return to them as questions arise or after completing a few exercises.


E: Expected behavior is supplied in each problem description and executable acceptance test.

In Low-Level Design (LLD):

  • Use SCOAT to construct the object model from expected behavior.
  • Use Executable design-stress tests to prove that the design survives pressure.
  • Use SOLID to audit the resulting boundaries, contracts, and dependencies.

Part 1: SOLID Principles

SOLID provides five design principles that keep object-oriented systems maintainable, decoupled, and robust under change.


1. Single Responsibility Principle (SRP)

Definition: A class or module should have one, and only one, reason to change. It must encapsulate a single cohesive responsibility.

❌ Violates SRP (One class doing multiple unrelated jobs)

class OrderManager:
    """Violates SRP: handles business calculation, persistence, and external notifications."""
    def calculate_total(self, order: dict) -> float:
        return sum(item["price"] * item["qty"] for item in order["items"])

    def save_to_database(self, order: dict) -> None:
        db_connection = "postgres://prod:5432/orders"
        print(f"Connecting to {db_connection} and saving order {order['id']}")

    def send_confirmation_email(self, order: dict) -> None:
        smtp_server = "smtp.mailservice.com"
        print(f"Sending confirmation email for order {order['id']} via {smtp_server}")

Why it fails: Changes to tax rules, database schemas, or email providers all require editing and re-testing OrderManager.

✅ Adheres to SRP (Each class has one clear reason to change)

class OrderCalculator:
    """Reason to change: financial calculation or pricing rules."""
    def calculate_total(self, order: dict) -> float:
        return sum(item["price"] * item["qty"] for item in order["items"])

class OrderRepository:
    """Reason to change: database schema or storage technology."""
    def save(self, order: dict) -> None:
        print(f"Persisting order {order['id']} to database")

class OrderNotifier:
    """Reason to change: communication channel or template formatting."""
    def notify(self, order: dict) -> None:
        print(f"Sending receipt for order {order['id']}")

Why it works: Each responsibility can change or be tested in complete isolation without impacting the others.


2. Open/Closed Principle (OCP)

Definition: Software entities should be open for extension, but closed for modification. You can introduce new behavior without rewriting existing, tested code.

❌ Violates OCP (Modifying central control code for every new variation)

class DiscountCalculator:
    """Violates OCP: adding a new customer tier requires editing this method."""
    def calculate_discount(self, customer_type: str, subtotal: float) -> float:
        if customer_type == "regular":
            return 0.0
        elif customer_type == "premium":
            return subtotal * 0.10
        elif customer_type == "vip":
            return subtotal * 0.20
        # Adding 'corporate' requires modifying this working method!
        raise ValueError(f"Unknown customer type: {customer_type}")

Why it fails: Every new discount rule risks breaking existing discount logic and requires re-testing the entire class.

✅ Adheres to OCP (Extending through polymorphism without modifying existing code)

from typing import Protocol

class DiscountPolicy(Protocol):
    def apply(self, subtotal: float) -> float:
        ...

class RegularDiscount:
    def apply(self, subtotal: float) -> float:
        return 0.0

class PremiumDiscount:
    def apply(self, subtotal: float) -> float:
        return subtotal * 0.10

class VipDiscount:
    def apply(self, subtotal: float) -> float:
        return subtotal * 0.20

# Adding a new discount requires zero edits to existing classes:
class CorporateDiscount:
    def apply(self, subtotal: float) -> float:
        return subtotal * 0.25

Why it works: New policies are plugged in without modifying the checkout orchestration or existing policies.


3. Liskov Substitution Principle (LSP)

Definition: Subtypes must be substitutable for their base types without breaking caller expectations, invalidating invariants, or throwing unexpected exceptions.

❌ Violates LSP (Subclass breaks the contract of the base class)

class BankAccount:
    def __init__(self, balance: float) -> None:
        self.balance = balance

    def withdraw(self, amount: float) -> None:
        if amount > self.balance:
            raise ValueError("Insufficient funds")
        self.balance -= amount

class FixedDepositAccount(BankAccount):
    """Violates LSP: throws an unexpected exception for a standard operation."""
    def withdraw(self, amount: float) -> None:
        raise RuntimeError("Withdrawals are locked until maturity date!")

Why it fails: Any function expecting a BankAccount will crash unexpectedly if passed a FixedDepositAccount.

✅ Adheres to LSP (Separate contracts preserve substitutability)

class Account:
    def __init__(self, balance: float) -> None:
        self.balance = balance

    def get_balance(self) -> float:
        return self.balance

class WithdrawableAccount(Account):
    def withdraw(self, amount: float) -> None:
        if amount > self.balance:
            raise ValueError("Insufficient funds")
        self.balance -= amount

class CheckingAccount(WithdrawableAccount):
    pass

class FixedDepositAccount(Account):
    """Adheres to LSP: only promises read balance, does not advertise withdraw."""
    pass

Why it works: Callers that require withdrawal accept WithdrawableAccount. All subclasses safely fulfill their advertised contracts.


4. Interface Segregation Principle (ISP)

Definition: Clients should not be forced to depend on methods they do not use. Prefer small, focused role interfaces over bloated, monolithic ones.

❌ Violates ISP (Bloated interface forcing dummy implementations)

from typing import Protocol

class SmartDevice(Protocol):
    def print_document(self) -> None: ...
    def scan_document(self) -> None: ...
    def fax_document(self) -> None: ...

class BasicDeskPrinter:
    """Violates ISP: forced to implement methods it cannot physically perform."""
    def print_document(self) -> None:
        print("Printing document...")

    def scan_document(self) -> None:
        raise NotImplementedError("Desk printer cannot scan!")

    def fax_document(self) -> None:
        raise NotImplementedError("Desk printer cannot fax!")

Why it fails: Clients calling scan_document() on a SmartDevice encounter unexpected runtime failures.

✅ Adheres to ISP (Segregated role protocols)

from typing import Protocol

class Printer(Protocol):
    def print_document(self) -> None: ...

class Scanner(Protocol):
    def scan_document(self) -> None: ...

class Fax(Protocol):
    def fax_document(self) -> None: ...

class BasicDeskPrinter:
    """Adheres to ISP: only implements Printer."""
    def print_document(self) -> None:
        print("Printing document...")

class AllInOneOfficeHub:
    """Adheres to ISP: implements Printer, Scanner, and Fax."""
    def print_document(self) -> None:
        print("Printing...")

    def scan_document(self) -> None:
        print("Scanning...")

    def fax_document(self) -> None:
        print("Faxing...")

Why it works: Clients depend only on the specific capability they need (e.g. def process_job(device: Printer): ...).


5. Dependency Inversion Principle (DIP)

Definition: 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.

❌ Violates DIP (High-level business logic tightly coupled to low-level details)

class SqliteDatabase:
    def execute_query(self, sql: str) -> None:
        print(f"Executing SQLite query: {sql}")

class OrderService:
    """Violates DIP: directly instantiates and depends on concrete SQLite driver."""
    def __init__(self) -> None:
        self.db = SqliteDatabase()

    def complete_order(self, order_id: str) -> None:
        self.db.execute_query(f"UPDATE orders SET status = 'DONE' WHERE id = '{order_id}'")

Why it fails: You cannot test OrderService without SQLite, and switching to Postgres or an in-memory mock requires editing OrderService.

✅ Adheres to DIP (Both depend on an abstraction; detail is injected)

from typing import Protocol

class DatabaseSession(Protocol):
    def execute_query(self, sql: str) -> None:
        ...

class SqliteDatabase:
    def execute_query(self, sql: str) -> None:
        print(f"SQLite: {sql}")

class PostgresDatabase:
    def execute_query(self, sql: str) -> None:
        print(f"Postgres: {sql}")

class OrderService:
    """Adheres to DIP: depends on DatabaseSession abstraction injected via constructor."""
    def __init__(self, db: DatabaseSession) -> None:
        self.db = db

    def complete_order(self, order_id: str) -> None:
        self.db.execute_query(f"UPDATE orders SET status = 'DONE' WHERE id = '{order_id}'")

Why it works: High-level domain orchestration is completely decoupled from database drivers. Testing is trivial with in-memory test doubles.


Part 2: The SCOAT Construction Framework

While SOLID audits the final object structure, SCOAT is the active step-by-step reasoning loop you use to construct the design from requirements under pressure.


1. S: Stable Roles

Focus: Identify enduring capabilities that callers rely on. A stable role is an essential capability, not an interface quota.

❌ Violates Stable Roles (Role fragmentation / confusing internal mechanics with roles)

class UserFirstNameValidator:
    def validate_first_name(self, name: str) -> bool:
        return bool(name)

class UserLastNameValidator:
    def validate_last_name(self, name: str) -> bool:
        return bool(name)

Why it fails: Fragmenting classes by individual fields creates an explosion of micro-objects with no enduring identity.

✅ Adheres to Stable Roles (Cohesive, enduring capability)

from typing import Protocol

class AccessController(Protocol):
    """Stable role: determines whether a principal may perform an action on a resource."""
    def is_permitted(self, subject: str, action: str, resource: str) -> bool:
        ...

Why it works: The capability is_permitted(...) is an enduring business capability. Whether the engine is RBAC, ABAC, or rule-based can vary freely behind this role.


2. C: Change (Variation Axes)

Focus: Identify the real variation axis that changes now or under the design-stress test. Do not build extension points for static code.

❌ Violates Change (Hardcoded variation flags inside orchestration)

class ShippingCalculator:
    """Violates Change: flags pollute the method signature whenever new criteria emerge."""
    def calculate_cost(self, weight: float, is_express: bool, is_international: bool, is_holiday: bool) -> float:
        base = weight * 2.0
        if is_express:
            base *= 1.5
        if is_international:
            base += 20.0
        if is_holiday:
            base += 5.0
        return base

Why it fails: Every new dimension of variation forces editing the signature, breaking callers and expanding combinatorial branching.

✅ Adheres to Change (Isolating the changing axis behind a policy)

from typing import Protocol

class RatePolicy(Protocol):
    def compute_rate(self, weight: float) -> float:
        ...

class StandardRatePolicy:
    def compute_rate(self, weight: float) -> float:
        return weight * 2.0

class ExpressInternationalPolicy:
    def compute_rate(self, weight: float) -> float:
        return (weight * 2.0 * 1.5) + 20.0

Why it works: The rate calculation axis varies independently without polluting or changing shipping orchestration.


3. O: Ownership & Lifetime

Focus: Establish who owns state, who mutates it, how long it lives, and where synchronization boundaries exist.

❌ Violates Ownership (Leaky state mutation across unmanaged boundaries)

class SharedTokenBucket:
    """Violates Ownership: exposes raw mutable state without synchronization or ownership."""
    def __init__(self, capacity: int) -> None:
        self.tokens = capacity  # Publicly mutable by any thread or caller!

# Caller code:
bucket = SharedTokenBucket(10)
# Thread A and Thread B race to decrement bucket.tokens directly:
bucket.tokens -= 1  # Race condition: lost updates, negative token counts under burst!

Why it fails: No single component owns the state or protects invariants under concurrent access.

✅ Adheres to Ownership (Encapsulated state, clear lifetime and concurrency boundary)

import threading
from typing import Callable

class TokenBucket:
    """Adheres to Ownership: strictly owns tokens, lock, and invariant state."""
    def __init__(self, capacity: int, refill_rate: float, clock: Callable[[], float]) -> None:
        self._capacity = capacity
        self._refill_rate = refill_rate
        self._clock = clock
        self._tokens = float(capacity)
        self._last_refill = clock()
        self._lock = threading.Lock()

    def allow(self) -> bool:
        with self._lock:
            now = self._clock()
            elapsed = now - self._last_refill
            self._tokens = min(float(self._capacity), self._tokens + elapsed * self._refill_rate)
            self._last_refill = now
            if self._tokens >= 1.0:
                self._tokens -= 1.0
                return True
            return False

Why it works: TokenBucket owns its lock, timestamp, and token counter. Callers cannot mutate internal state or bypass thread safety.


4. A: Abstraction Need

Focus: Ask whether an abstraction is genuinely required. Introduce a boundary only for demonstrated variation, substitution, or isolation. “No additional abstraction” is a valid, high-craft answer.

❌ Violates Abstraction Need (Speculative over-engineering without requirement pressure)

# Over-engineered for a simple single-formula system with zero variation pressure:
class IMetricIdProvider(Protocol):
    def get_id(self) -> str: ...

class IMetricValueProvider(Protocol):
    def get_value(self) -> float: ...

class IMetricFactory(Protocol):
    def create_metric(self) -> tuple[IMetricIdProvider, IMetricValueProvider]: ...

Why it fails: High cognitive load, boilerplate indirection, and zero business value when metrics are simply key-value numbers.

✅ Adheres to Abstraction Need (Right-sized design matching the actual pressure)

from dataclasses import dataclass

@dataclass(frozen=True)
class Metric:
    """Adheres to Abstraction Need: simple immutable value object until variation demands more."""
    name: str
    value: float

Why it works: Direct, readable code without speculative interfaces. When real pressure (e.g. streaming telemetry, distributed aggregation) arrives, refactoring is targeted and justified.


5. T: Topology

Focus: Establish clean runtime containment, acyclic delegation, execution order, and explicit failure paths.

❌ Violates Topology (Cyclic calls, tangled back-references, spaghetti flow)

class Order:
    def __init__(self) -> None:
        self.payment = PaymentService()

    def checkout(self) -> None:
        self.payment.process(self)  # Order calls PaymentService

class PaymentService:
    def process(self, order: Order) -> None:
        # PaymentService calls back into Order, mutating it:
        order.status = "PAID"
        # And calls notification, which calls back into Order:
        NotificationService().alert(order)

class NotificationService:
    def alert(self, order: Order) -> None:
        order.notification_sent = True  # Hidden back-channel mutation!

Why it fails: Circular call flow makes debugging, testing, and error recovery impossible when a failure occurs mid-cycle.

✅ Adheres to Topology (Unidirectional, acyclic call pipeline)

class OrderCoordinator:
    """Adheres to Topology: clear top-down execution flow with no circular dependencies."""
    def __init__(self, payment_gateway: PaymentGateway, notifier: OrderNotifier) -> None:
        self._payment_gateway = payment_gateway
        self._notifier = notifier

    def checkout(self, order: Order) -> OrderResult:
        # Step 1: Charge payment
        charge_result = self._payment_gateway.charge(order.id, order.total)
        if not charge_result.success:
            return OrderResult(success=False, error=charge_result.error)

        # Step 2: Notify (only after payment succeeds)
        self._notifier.notify(order)
        return OrderResult(success=True)

Why it works: Unidirectional pipeline: Coordinator delegates down to PaymentGateway and Notifier. No component holds circular back-references.


Summary: How to Build and Audit LLD

StepActionQuestion to Ask
EExpected BehaviorWhat is the observable caller contract and acceptance example?
SStable RolesWhat enduring capabilities do callers rely on?
CChangeWhat axis actually varies under the stated pressure?
OOwnershipWho owns the state, lifetime, mutation, and concurrency lock?
AAbstraction NeedIs an abstraction genuinely justified, or is concrete code simpler?
TTopologyIs the runtime call graph clean, acyclic, and unidirectional?
AuditSOLIDDoes the resulting design honor SRP, OCP, LSP, ISP, and DIP?
Sign in with an enabled provider to save your lesson progress.
Sign in to track progress

Loading sign-in options…