Core Principles
What you’ll learn. Why software design is fundamentally about managing complexity; how cohesion and coupling give you a vocabulary for “good structure”; the five SOLID principles with code showing violations and fixes; when DRY, KISS and YAGNI help and when they mislead; and why modern designs prefer composition over inheritance. Examples are labelled Python or TypeScript.
The real enemy: complexity
Section titled “The real enemy: complexity”Software is easy to write and hard to change. The cost of a codebase over its lifetime is dominated by reading and modifying existing code, not writing it. John Ousterhout (A Philosophy of Software Design) defines complexity operationally: anything about the structure of a system that makes it hard to understand and modify. Its symptoms are:
- Change amplification: a simple change requires edits in many places.
- Cognitive load: you must hold a lot in your head to make a change safely.
- Unknown unknowns: it is not obvious what code is affected, or what you need to know.
Its causes are two things: dependencies (code that cannot be understood or changed in isolation) and obscurity (important information is not obvious). Nearly every principle in this lecture is a strategy for reducing dependencies or obscurity.
A useful mental model: complexity is incremental. No single hack ruins a system; a thousand “just this once” decisions do. Design is therefore a continuous, small-scale discipline rather than a phase.
Cohesion and coupling
Section titled “Cohesion and coupling”These two terms (from structured design, Constantine and Yourdon, 1970s) remain the sharpest tools for judging structure.
Cohesion measures how strongly the elements inside a module belong together. A module with high cohesion does one conceptual thing: a Money class that handles amounts and currency arithmetic. Low cohesion is the Utils or Helpers grab bag.
Coupling measures how strongly different modules depend on each other. Low coupling means you can change one module without touching others.
The goal: high cohesion, low coupling. They are linked: if related things are scattered (low cohesion), modules must talk to each other a lot (high coupling).
Coupling comes in kinds, roughly from worst to best:
| Kind | Example |
|---|---|
| Content | Module A reaches into B’s internals / mutates private state |
| Common | Both modules read/write the same global variable |
| Control | A passes a flag telling B how to behave |
| Stamp | A passes a whole object when B needs only one field |
| Data | A passes only the primitive values B needs |
| Message | A sends a message through a narrow interface; B decides what to do |
Practical coupling also includes temporal coupling (calls must happen in a given order) and connascence (Meilir Page-Jones): two components are connascent if a change in one requires a change in the other. Connascence of name (you must agree on a function’s name) is weak and acceptable; connascence of position (argument order) or meaning (magic numbers) is stronger and should be kept local.
# Python: stamp coupling vs data couplingdef shipping_cost(order) -> float: # needs the whole Order class return order.weight_kg * 2.5
def shipping_cost(weight_kg: float) -> float: # depends only on what it uses return weight_kg * 2.5Abstraction and information hiding
Section titled “Abstraction and information hiding”An abstraction is a simplified view of something that omits unimportant details. In code, the interface is the abstraction, the implementation is what is hidden. David Parnas’s 1972 paper “On the Criteria To Be Used in Decomposing Systems into Modules” argued that modules should be drawn around design decisions likely to change, hiding each decision behind an interface. This is information hiding, and it is arguably the single most important idea in software design.
Ousterhout’s corollary: prefer deep modules, those with a simple interface that hides a lot of functionality (the Unix file API: open/read/write/close hides disk layout, caching, permissions). Beware shallow modules, whose interface is nearly as complex as the implementation; a class with ten one-line getters and setters adds a layer without hiding anything.
Deep module Shallow module+-----------+ narrow +--------------------------+ wide| interface | interface | interface | interface+-----------+ +--------------------------+| | | tiny implementation || lots of | +--------------------------+| hidden || logic |+-----------+Leaky abstractions (Joel Spolsky’s term) are unavoidable at some level: TCP pretends to be a reliable stream but you still see timeouts. Good design makes leaks rare and obvious.
SOLID is a mnemonic by Robert C. Martin for five object-oriented design principles. They are heuristics, not laws, and are best understood as consequences of “high cohesion, low coupling”.
S: Single Responsibility Principle
Section titled “S: Single Responsibility Principle”A module should have one, and only one, reason to change. (Martin: it should be responsible to one actor.)
The key is “reason to change”, not “does one thing”. A class that computes payroll and formats the report and writes to the database has three reasons to change (business rules, presentation, persistence).
// TypeScript: violationclass Invoice { constructor(public items: { price: number; qty: number }[]) {} total(): number { return this.items.reduce((s, i) => s + i.price * i.qty, 0); } toHtml(): string { return `<p>Total: ${this.total()}</p>`; } // presentation save(db: Database): void { db.insert("invoices", this); } // persistence}
// Better: split by reason to changeclass Invoice { constructor(readonly items: { price: number; qty: number }[]) {} total(): number { return this.items.reduce((s, i) => s + i.price * i.qty, 0); }}const renderInvoiceHtml = (inv: Invoice) => `<p>Total: ${inv.total()}</p>`;interface InvoiceRepository { save(inv: Invoice): void }Over-applying SRP produces dozens of tiny classes with no cohesion. Split on genuine axes of change, not hypothetical ones.
O: Open/Closed Principle
Section titled “O: Open/Closed Principle”Software entities should be open for extension but closed for modification.
You should be able to add behavior without editing tested, working code. The typical mechanism is polymorphism or a data-driven table.
# Python: violation, every new shape edits this functiondef area(shape): if shape["kind"] == "circle": return 3.14159 * shape["r"] ** 2 elif shape["kind"] == "rect": return shape["w"] * shape["h"]
# Open for extension: add a new class, touch nothing elsefrom typing import Protocolimport math
class Shape(Protocol): def area(self) -> float: ...
class Circle: def __init__(self, r: float): self.r = r def area(self) -> float: return math.pi * self.r ** 2
class Rect: def __init__(self, w: float, h: float): self.w, self.h = w, h def area(self) -> float: return self.w * self.h
def total_area(shapes: list[Shape]) -> float: return sum(s.area() for s in shapes)Caveat: this is the “expression problem”. Polymorphism makes adding new types easy but adding new operations hard (every class changes); a switch/visitor does the opposite. You choose which axis to keep open (see the behavioral patterns lecture on Visitor).
L: Liskov Substitution Principle
Section titled “L: Liskov Substitution Principle”If
Sis a subtype ofT, objects of typeTmay be replaced with objects of typeSwithout breaking the program’s correctness.
Subtyping is about behavioral compatibility, not just matching signatures. A subtype must: accept at least what the parent accepts (preconditions not strengthened), guarantee at least what the parent guarantees (postconditions not weakened), preserve invariants, and not throw new exception types the caller does not expect.
Classic violation: Square extends Rectangle. A Rectangle has independent width and height; a Square must keep them equal, so code that sets width to 5 and height to 4 and expects area 20 breaks.
class Rectangle: def __init__(self, w, h): self.w, self.h = w, h def set_w(self, w): self.w = w def set_h(self, h): self.h = h def area(self): return self.w * self.h
class Square(Rectangle): # violates LSP def set_w(self, w): self.w = self.h = w def set_h(self, h): self.w = self.h = h
def stretch(r: Rectangle): r.set_w(5); r.set_h(4) assert r.area() == 20 # fails for SquareThe fix is usually not to model “is-a” in the real-world sense, but to ask what behavior callers rely on. Immutable value shapes avoid this trap entirely.
I: Interface Segregation Principle
Section titled “I: Interface Segregation Principle”Clients should not be forced to depend on methods they do not use.
Prefer several small, role-specific interfaces to one fat one. In Go and TypeScript, structural typing makes this cheap: define the interface at the consumer.
// Fat interface forces every implementer to stub irrelevant methodsinterface Worker { work(): void; eat(): void; sleep(): void }
// Segregatedinterface Workable { work(): void }interface Feedable { eat(): void }
function runShift(w: Workable) { w.work(); } // a robot qualifiesD: Dependency Inversion Principle
Section titled “D: Dependency Inversion Principle”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.
Without inversion, business logic imports the database driver, so the policy depends on the mechanism. With inversion, the business logic owns an interface (a “port”) and the database adapter implements it. The source-code dependency points opposite to the control flow.
Before: OrderService ----> PostgresClientAfter: OrderService ----> <<OrderRepository>> <---- PostgresOrderRepository (policy) (abstraction, owned by policy) (detail)from typing import Protocol
class OrderRepository(Protocol): def save(self, order: "Order") -> None: ...
class OrderService: def __init__(self, repo: OrderRepository): # injected self.repo = repo def place(self, order: "Order") -> None: # business rules... self.repo.save(order)
class InMemoryOrderRepository: # also useful in tests def __init__(self): self.orders = [] def save(self, order): self.orders.append(order)DIP is the foundation of hexagonal architecture (Architecture Styles) and of dependency injection (Creational Patterns). Note: dependency inversion (a design principle), dependency injection (a technique), and IoC containers (a tool) are three different things.
DRY, KISS, YAGNI
Section titled “DRY, KISS, YAGNI”DRY: Don’t Repeat Yourself
Section titled “DRY: Don’t Repeat Yourself”From The Pragmatic Programmer: “Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.” The emphasis is on knowledge, not text. Two code blocks that look identical but encode different business rules should not be merged; they will diverge, and the merged abstraction will sprout flags to tell them apart. Conversely, the same rule expressed in a SQL constraint, a validation function and a front-end check is a real DRY violation even if the code looks different.
Heuristic: the rule of three: tolerate duplication until the third occurrence, because by then the real shape of the abstraction is visible. Sandi Metz: “duplication is far cheaper than the wrong abstraction.”
KISS: Keep It Simple
Section titled “KISS: Keep It Simple”Prefer the simplest design that works. Simple is not the same as easy: simple means few interleaved concerns (Rich Hickey, “Simple Made Easy”). A 200-line function with obvious flow can be simpler than a clever, 30-line metaprogramming trick that no colleague can debug.
YAGNI: You Aren’t Gonna Need It
Section titled “YAGNI: You Aren’t Gonna Need It”Don’t build features or generality for needs you merely anticipate. Speculative generality is cost with uncertain payoff: you pay for design, tests and maintenance now, and the guess is usually wrong. YAGNI does not mean ignore design; it means keep the code easy to change (clean, tested, decoupled) so that adding the feature later is cheap. Martin Fowler’s caveat: YAGNI applies to presumptive features, not to effort on making software malleable.
Where they conflict
Section titled “Where they conflict”DRY pushes toward abstraction; YAGNI and KISS push against premature abstraction. The reconciling heuristic: abstract on the third use, hide on the first. Hide decisions (information hiding) early because it is cheap; generalize later when you have evidence.
Composition over inheritance
Section titled “Composition over inheritance”Inheritance couples subclass to parent’s implementation, not just its interface (the “fragile base class problem”). Deep hierarchies make behavior hard to trace, force a single axis of variation, and break LSP easily. Composition assembles behavior from collaborating objects, each swappable.
# Inheritance: combinatorial explosionclass Duck: ...class FlyingDuck(Duck): ...class SwimmingFlyingDuck(FlyingDuck): ...# A rubber duck that does neither? A robot duck that flies but never swims?
# Composition: behaviors are partsclass Duck: def __init__(self, fly_behavior, swim_behavior): self.fly = fly_behavior self.swim = swim_behavior def perform_fly(self): return self.fly()
fly_wings = lambda: "flap"no_fly = lambda: "..."rubber = Duck(no_fly, lambda: "float")This is the Strategy pattern in disguise. Inheritance still has legitimate uses: genuine “is-a” with Liskov-compliant behavior, shared framework base classes, and sealed hierarchies (algebraic data types) where the set of subtypes is closed and known. A good rule: inherit for type (interface) relationships, compose for code reuse. Mixins, traits (Rust), and default interface methods (Java, Kotlin) are middle grounds.
Managing complexity in practice
Section titled “Managing complexity in practice”Beyond named principles, these habits repeatedly pay off:
-
Make illegal states unrepresentable. Use types to encode invariants. In TypeScript, a discriminated union beats a bag of optional fields:
type Request =| { state: "loading" }| { state: "ok"; data: string }| { state: "error"; error: Error }; -
Pull complexity downward. Better for a module to be internally complex than to push complexity onto every caller (Ousterhout). Provide sensible defaults.
-
Define errors out of existence. Design APIs so that edge cases are normal cases (deleting a nonexistent key is a no-op, not an exception).
-
Separate policy from mechanism, and pure from effectful code. Functional core, imperative shell: put decisions in pure functions that are trivial to test and push I/O to the edges.
-
Name things well. If you cannot find a simple name, the abstraction is probably unclear.
-
Comments explain why, not what. Document the non-obvious, the invariants and the interface contract.
-
Strategic over tactical programming. Invest a small, constant fraction of time (Ousterhout suggests roughly 10-20%) in design improvement rather than shipping the quickest patch each time.
Common pitfalls
Section titled “Common pitfalls”- Interface for every class. A single-implementation interface that never varies is ceremony. Introduce abstractions at real seams (I/O boundaries, genuine variation points).
- Premature DRY. Merging coincidentally similar code.
- Inheritance for reuse rather than substitutability.
- God objects and
Manager/Utilclasses: low cohesion. - Cargo-culting patterns. Patterns (next lectures) are solutions to specific forces; applying them without the forces adds complexity.
Key takeaways
Section titled “Key takeaways”- Complexity (dependencies + obscurity) is the central problem; design is how you contain it.
- Aim for high cohesion and low coupling; prefer data/message coupling over content/common coupling.
- Hide design decisions likely to change behind deep, narrow interfaces (Parnas).
- SOLID: one reason to change (S); extend without editing (O); subtypes honor behavioral contracts (L); small consumer-owned interfaces (I); depend on abstractions you own (D).
- DRY is about knowledge, not text; use rule of three; the wrong abstraction costs more than duplication.
- YAGNI against speculative features, but keep code malleable.
- Prefer composition for reuse and inheritance only for true substitutable subtyping.
Exercises
Section titled “Exercises”- Conceptual. A
Userclass hasvalidateEmail(),saveToDb(),sendWelcomeEmail()andtoJson(). Name the separate reasons to change and propose a decomposition. - Conceptual. Give an example where two identical-looking functions should not be deduplicated. What would go wrong?
- Hands-on (Python). Rewrite
def discount(kind, amt): if kind == "vip": ... elif kind == "staff": ...so that adding a new discount type requires no edit to existing functions. What trade-off does this introduce regarding adding new operations? - Hands-on (TypeScript). Model a payment as
{method, cardNumber?, iban?, paypalEmail?}and refactor into a discriminated union. Which invalid states disappear? - Conceptual. Why does
Square extends Rectangleviolate LSP even though it type-checks? Suggest two designs that avoid the issue.
Solutions (sketch)
- Validation rules (domain), persistence (infrastructure), email (notification/messaging), serialization (presentation/API format). Keep
Useras data + invariants; addUserRepository,WelcomeMailer, and a serializer. - Two tax rules for different countries that currently share a rate. When one country changes its rate, the shared function needs a country flag; the abstraction accrues conditionals.
- Use a dict mapping kind to a callable/class (Strategy). Adding operations (e.g. “describe discount”) now requires touching every entry: the expression problem.
- Union members
{method:"card", cardNumber},{method:"sas", iban},{method:"paypal", email}; impossible: card payment with an IBAN only, or no identifier. - Callers expect independent width/height; Square’s setters couple them, breaking the postcondition. Options: make shapes immutable with
Square(side)andRectangle(w,h)both implementing aShapeinterface; or drop inheritance and use composition.
Further reading
Section titled “Further reading”- John Ousterhout, A Philosophy of Software Design (2nd ed., 2021).
- Robert C. Martin, Clean Architecture (2017); the SOLID articles originate from his 2000 paper “Design Principles and Design Patterns”.
- David Parnas, “On the Criteria To Be Used in Decomposing Systems into Modules” (1972).
- Andrew Hunt and David Thomas, The Pragmatic Programmer (20th anniversary ed., 2019).
- Barbara Liskov and Jeannette Wing, “A Behavioral Notion of Subtyping” (1994).
- Rich Hickey, “Simple Made Easy” (Strange Loop talk, 2011).
- Meilir Page-Jones, What Every Programmer Should Know About Object-Oriented Design (1995), on connascence.