Shelves / Software Architecture
SA·136
SOLID
The five SOLID principles from first principles, each with its original intent, a violation and refactoring in several languages, how it looks in functional, procedural and systems programming, and when applying it blindly hurts: Single Responsibility (reasons to change, actors), Open/Closed (extension points, sealed types and the expression problem), Liskov Substitution (behavioural subtyping, contracts, the rectangle-square trap), Interface Segregation (role interfaces, Go's small interfaces, Rust traits), and Dependency Inversion (ports, ownership of abstractions, DI), plus composition over inheritance and companion principles (DRY, KISS, YAGNI, GRASP).
Start here: five rules for parts that fit together
SOLID is five principles for object-oriented design, collected by Robert C. Martin. Each one reduces a specific kind of change cost:
| Letter | Principle | In one line |
|---|---|---|
| S | Single responsibility | a module should have one reason to change (one stakeholder) |
| O | Open/closed | add behaviour by adding code, not by editing working code |
| L | Liskov substitution | a subtype must be usable anywhere its base type is, without surprises |
| I | Interface segregation | clients shouldn't depend on methods they don't use |
| D | Dependency inversion | high-level policy depends on abstractions; details plug in |
The Start Here chapter already showed O (wallets added as a new class) and D (gateways passed in). The experiments below test L, I and D with numbers.
Liskov: a subtype that breaks callers
A MenuStore promises: after put(k, v), get(k) returns v; get of a missing key returns None. Five implementations, one set of contract tests run against all of them:
memory 3 of 3 passed
file 3 of 3 passed
postgres 3 of 3 passed
uppercase FAILED get_returns_what_was_put, put_overwrites ← stores "DAL TADKA" when given "Dal Tadka"
strict FAILED missing_key_is_none ← raises KeyError instead of returning None
UpperCaseStore and StrictStore each looked like a harmless improvement ("normalise names", "fail loudly"). But code written against MenuStore (like the menu service's get(...) or "Thali of the day") breaks when handed either one. That's a Liskov violation: same method names, different promises. Running the base type's contract tests against every subtype is the practical way to catch it.
Interface segregation: small interfaces get used
Go's standard library is designed around tiny interfaces. Counting its source:
exported interfaces: 221; 89 of them (40%) have exactly one method
types implementing Read(p []byte): at least 43; Write(p []byte): at least 36
functions accepting an io.Reader parameter: 246
Because io.Reader asks for just one method, files, network connections, compressors, decryptors, HTTP bodies and in-memory buffers all satisfy it, and 246 functions accept any of them. A fat "Storage" interface with twenty methods would get few implementations and force each one to stub methods it can't support.
Dependency inversion: tests that don't need the database
The menu service depends on the MenuStore abstraction, not on PostgreSQL. The same 400 tests, run with each store plugged in:
injected in-memory store: 400 passed in 0.31 s
real PostgreSQL store: 400 passed in 3.84 s
Twelve times faster, with no database to set up, because the business rule ("trim the name, reject empty, fall back to the default") doesn't depend on storage details. The PostgreSQL store is still tested, once, by the contract tests above.
How deep to go in SOLID
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | State the five principles and recognise obvious violations |
| L2 | Apply them when adding features: new behaviour as new types, dependencies injected |
| L3 | Explain the original intent of each, how they look in functional and systems code, and their costs |
| L4 | Find violations with contract tests, dependency analysis and change history, and refactor them |
| L5 | Decide where abstractions are worth it in a codebase and where they're ceremony |
| L6 | Teach and set design standards that balance flexibility against simplicity |
Where SOLID comes from
SOLID is an acronym coined by Michael Feathers for five principles collected by Robert C. Martin around 2000, drawing on earlier work by Bertrand Meyer (Open/Closed, 1988), Barbara Liskov (substitution, 1987) and others. They were formulated for object-oriented class design, but their underlying ideas (separate things that change for different reasons; extend without modifying; honour contracts; depend on narrow interfaces; point dependencies toward stable policy) apply to functions, modules, packages and services in any paradigm.
| Principle | One-line essence | Main enemy |
|---|---|---|
| Single Responsibility | A module should have one reason to change (serve one actor) | Divergent change, merge conflicts between teams |
| Open/Closed | Extend behaviour without modifying stable code | Ripple-effect edits, regressions |
| Liskov Substitution | Subtypes must be usable wherever their base type is expected | Surprising runtime failures, instanceof checks |
| Interface Segregation | Clients shouldn't depend on methods they don't use | Fat interfaces, unnecessary recompilation and coupling |
| Dependency Inversion | High-level policy shouldn't depend on low-level details; both depend on abstractions | Business logic tied to frameworks and infrastructure |
Single Responsibility Principle
The real meaning
The popular phrasing "a class should do one thing" is misleading. Martin's refined definition: a module should be responsible to one, and only one, actor, i.e. it should have one reason to change, where reasons come from the people or business forces that request changes.
Classic example: an Employee class with calculatePay() (owned by finance/CFO), reportHours() (owned by HR/COO) and save() (owned by DBAs/CTO). If calculatePay and reportHours share a helper for "regular hours", a change requested by finance silently changes HR's reports. The problem isn't the class being "big"; it's that different actors' requirements are entangled.
// Violation: three actors' concerns in one class sharing internals
class Employee {
Money calculatePay() { /* uses regularHours() */ }
HoursReport reportHours() { /* also uses regularHours() */ }
void save() { /* SQL */ }
private Hours regularHours() { /* changing this for payroll breaks HR reports */ }
}
// SRP: separate modules per actor, sharing only the data
record EmployeeData(EmployeeId id, String name, List<TimeEntry> timesheet, PayRate rate) {}
final class PayCalculator { Money pay(EmployeeData e) { /* finance's rules */ } }
final class HoursReporter { HoursReport report(EmployeeData e) { /* HR's rules */ } }
final class EmployeeStore { void save(EmployeeData e) { /* persistence */ } }
// Go: separate packages per responsibility; the data type is shared, logic isn't
// package payroll
func Pay(e employee.Data, rules Rules) money.Amount { /* ... */ }
// package hrreport
func Hours(e employee.Data) Report { /* ... */ }
// package employeestore
func (s *Store) Save(ctx context.Context, e employee.Data) error { /* ... */ }
# Python: functions grouped by concern in separate modules
# payroll.py
def pay(employee: EmployeeData, rules: PayRules) -> Money: ...
# hr_reports.py
def hours_report(employee: EmployeeData) -> HoursReport: ...
# employee_repo.py
class EmployeeRepository:
def save(self, employee: EmployeeData) -> None: ...
SRP at other scales
- Functions: one level of abstraction (chapter 135).
- Modules/packages: organised by business capability so a feature request touches one place (Common Closure Principle: classes that change together belong together).
- Services: a microservice should align with one bounded context and one team (chapter 141).
- Functional programming: modules of pure functions around one concept; data and functions separated, but cohesion by domain still applies.
When SRP hurts
- Splitting by imagined reasons to change creates many tiny classes with scattered logic (shallow modules). Split when you observe divergent change, or when different actors clearly own different rules.
- Over-splitting a cohesive algorithm across classes makes it harder to read than one well-structured module.
Open/Closed Principle
The idea
Bertrand Meyer (1988): software entities should be open for extension, closed for modification. Adding a new variant of behaviour (a new payment method, a new export format, a new discount rule) should mean adding code, not editing existing, tested code in many places.
Mechanisms:
- Polymorphism via interfaces/traits: new implementations plug in.
- Strategy objects or first-class functions: pass behaviour as data.
- Plugin registries: implementations register themselves (Java
ServiceLoader, Spring beans collected into aList<Handler>, Goinit()registration indatabase/sqldrivers, Python entry points). - Configuration and data-driven rules: behaviour determined by data (rule tables) rather than code edits.
- Middleware/decorators: add cross-cutting behaviour without changing the core (chapter 137).
// Violation: every new payment method edits this switch (and others like it elsewhere)
Money fee(Payment p) {
return switch (p.method()) {
case "CARD" -> p.amount().percent(2);
case "UPI" -> Money.zero();
case "WALLET" -> p.amount().percent(1);
default -> throw new IllegalArgumentException();
};
}
// OCP: each method is a plug-in; adding one = a new class registered as a bean
public interface PaymentMethod {
String code();
Money fee(Money amount);
AuthorizationResult authorize(PaymentRequest req);
}
@Component class CardPayments implements PaymentMethod { /* ... */ }
@Component class UpiPayments implements PaymentMethod { /* ... */ }
@Service
class PaymentMethods {
private final Map<String, PaymentMethod> byCode;
PaymentMethods(List<PaymentMethod> methods) { // Spring injects all implementations
this.byCode = methods.stream().collect(toMap(PaymentMethod::code, m -> m));
}
PaymentMethod get(String code) { return Optional.ofNullable(byCode.get(code)).orElseThrow(); }
}
// Go: registry pattern, as used by database/sql drivers and image decoders
type PaymentMethod interface {
Fee(amount Money) Money
Authorize(ctx context.Context, req Request) (Result, error)
}
var methods = map[string]PaymentMethod{}
func Register(code string, m PaymentMethod) { methods[code] = m } // called from each method's init()
// package upi
func init() { payments.Register("UPI", upiMethod{}) }
// Rust: trait objects for open extension
pub trait PaymentMethod: Send + Sync {
fn code(&self) -> &'static str;
fn fee(&self, amount: Money) -> Money;
}
pub struct Registry { methods: HashMap<&'static str, Box<dyn PaymentMethod>> }
impl Registry {
pub fn with(mut self, m: impl PaymentMethod + 'static) -> Self {
self.methods.insert(m.code(), Box::new(m)); self
}
}
// TypeScript: functions as strategies, keyed in a record
type FeeRule = (amount: Money) => Money;
const feeRules: Record<string, FeeRule> = {
CARD: (a) => a.percent(2),
UPI: () => Money.zero(),
};
export const registerFeeRule = (code: string, rule: FeeRule) => { feeRules[code] = rule; };
OCP and the expression problem
There are two axes of extension: adding new types/variants and adding new operations. Philip Wadler named the tension the expression problem:
- With interfaces/polymorphism (OOP style), adding a new variant is easy (new class), but adding a new operation means editing every class.
- With sum types and pattern matching (functional style: Haskell ADTs, Rust enums, Java sealed interfaces +
switch, Kotlin sealed classes, TypeScript discriminated unions), adding a new operation is easy (new function with amatch), but adding a new variant means updating every match. The compiler's exhaustiveness checking points out each one, which turns "modification" into a safe, guided change.
// Rust: closed set of variants, open set of operations; exhaustiveness checking guides changes
pub enum Shape { Circle { r: f64 }, Rect { w: f64, h: f64 } }
pub fn area(s: &Shape) -> f64 {
match s { Shape::Circle { r } => std::f64::consts::PI * r * r, Shape::Rect { w, h } => w * h }
}
pub fn perimeter(s: &Shape) -> f64 { // new operation: just add a function
match s { Shape::Circle { r } => 2.0 * std::f64::consts::PI * r, Shape::Rect { w, h } => 2.0 * (w + h) }
}
// Adding Shape::Triangle makes every match a compile error until handled: modification, but guided.
Choose by which axis changes more often: payment methods (new variants arrive regularly, operations stable) → interfaces/plugins; AST nodes or domain events (variants fairly stable, new analyses frequently) → sealed types and pattern matching. Type classes (Haskell), traits with blanket implementations (Rust), and the visitor pattern offer further trade-offs.
When OCP hurts
- Building extension points for variation that never arrives (speculative generality): every plugin interface adds indirection and cognitive load.
- Rule of thumb: let the second or third concrete need drive the abstraction; before that, a simple
switchis clearer. Modern sealed types with exhaustive matching make a switch a perfectly principled design.
Liskov Substitution Principle
Behavioural subtyping
Barbara Liskov (1987, formalised with Jeannette Wing in 1994): if S is a subtype of T, objects of type T may be replaced with objects of type S without altering the desirable properties of the program. Type systems check signatures; LSP is about behaviour:
- Preconditions can't be strengthened in a subtype (it must accept everything the base accepts).
- Postconditions can't be weakened (it must guarantee at least what the base guarantees).
- Invariants of the base must be preserved.
- No new exceptions that callers of the base type don't expect.
- History constraint: a subtype can't allow state changes the base type forbids (a mutable subtype of an immutable type).
The rectangle-square trap
class Rectangle {
protected int w, h;
void setWidth(int w) { this.w = w; }
void setHeight(int h) { this.h = h; }
int area() { return w * h; }
}
class Square extends Rectangle { // "a square IS-A rectangle" mathematically…
@Override void setWidth(int w) { this.w = w; this.h = w; }
@Override void setHeight(int h) { this.w = h; this.h = h; }
}
void stretch(Rectangle r) {
r.setWidth(5); r.setHeight(4);
assert r.area() == 20; // fails for Square (16): Square violates Rectangle's contract
}
The mathematical "is-a" relation doesn't imply behavioural substitutability for mutable objects. Fixes: make shapes immutable values (a square is a valid rectangle value), or don't relate them by inheritance (separate types implementing a common Shape with area()).
Real-world LSP violations:
Collections.unmodifiableListreturns aListwhoseaddthrowsUnsupportedOperationException: callers expecting a modifiable list fail at runtime (a known compromise in Java's collection design; Kotlin separatesListandMutableList).- A
ReadOnlyFilesubclass ofFilethrowing onwrite. - A caching repository that returns stale data where the interface promised read-your-writes.
- An implementation of a
Queueinterface that silently drops items when full while the contract promised blocking. - A "fake" in tests that behaves differently from the real implementation (Vol. 11 ch. 115: run shared contract tests against both).
LSP beyond inheritance
LSP applies to any substitution: interface implementations, duck typing, plug-ins, service versions behind the same API (a new service version must honour the old contract for existing clients: chapter 141), and test doubles. Contract tests that every implementation must pass are the practical tool:
# Shared contract test suite run against every implementation of a KeyValueStore
import pytest
class KeyValueStoreContract:
@pytest.fixture
def store(self): raise NotImplementedError
def test_get_returns_what_was_put(self, store):
store.put("k", b"v")
assert store.get("k") == b"v"
def test_missing_key_returns_none(self, store):
assert store.get("absent") is None
def test_delete_is_idempotent(self, store):
store.delete("absent") # must not raise
class TestInMemoryStore(KeyValueStoreContract):
@pytest.fixture
def store(self): return InMemoryStore()
class TestRedisStore(KeyValueStoreContract):
@pytest.fixture
def store(self, redis_container): return RedisStore(redis_container.url)
Variance
LSP also underlies variance rules in type systems: function parameters are contravariant (a function accepting Animal can substitute for one accepting Dog), return types covariant. Java's ? extends/? super (PECS: producer extends, consumer super), Kotlin's out/in, C#'s out/in, Scala's +/-, TypeScript's (mostly bivariant method parameters, strict function types), and Rust's variance on lifetimes encode this.
Interface Segregation Principle
Role interfaces
Clients should not be forced to depend on methods they do not use. A "fat" interface couples every client to every method: changes to unrelated methods force recompilation or redeployment, implementations must stub out irrelevant methods (often throwing, which then violates LSP), and test doubles become large.
Fix: role interfaces defined from the client's point of view, each with the few methods that client needs. One class can implement many role interfaces.
// Go embodies ISP: small interfaces, defined where they're consumed, satisfied implicitly
type OrderReader interface {
Order(ctx context.Context, id OrderID) (Order, error)
}
type ShippingNotifier struct{ orders OrderReader } // needs only reads, depends only on reads
// Standard library examples: io.Reader, io.Writer, io.Closer composed as io.ReadWriteCloser;
// fmt.Stringer; sort.Interface. "The bigger the interface, the weaker the abstraction." (Rob Pike)
// Java: split a fat repository interface into role interfaces
// Before: every client sees 20 methods
interface OrderRepository { Order find(OrderId id); List<Order> search(Query q); void save(Order o);
void delete(OrderId id); Stats stats(); void reindex(); /* ... */ }
// After: clients depend on what they use; one class can implement all
interface OrderLookup { Optional<Order> find(OrderId id); }
interface OrderSearch { Page<Order> search(OrderQuery q, PageRequest page); }
interface OrderWriter { void save(Order o); }
final class JdbcOrders implements OrderLookup, OrderSearch, OrderWriter { /* ... */ }
// Rust: fine-grained traits; functions require only the bounds they need
pub trait Read { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>; }
pub trait Write { fn write(&mut self, buf: &[u8]) -> io::Result<usize>; fn flush(&mut self) -> io::Result<()>; }
fn copy_all<R: Read, W: Write>(r: &mut R, w: &mut W) -> io::Result<u64> { /* ... */ }
// std::io::Read and Write are separate; a type implements whichever it supports.
// TypeScript: structural typing means a function can require just the shape it needs
interface Clock { now(): Date }
export function isExpired(token: { expiresAt: Date }, clock: Clock): boolean {
return clock.now() > token.expiresAt; // accepts any object with expiresAt, not the whole Token class
}
ISP at other scales
- APIs: give different clients different endpoints/views rather than one mega-endpoint (BFFs, GraphQL letting clients select fields).
- Microservices: consumers depend on narrow contracts; consumer-driven contract tests reveal which fields are actually used (Vol. 11 ch. 117).
- Modules: expose small public surfaces; keep the rest internal.
When ISP hurts
Splitting every interface into single-method pieces by reflex creates a proliferation of tiny types that obscure what a component does. Segregate around real client roles and observed coupling problems.
Dependency Inversion Principle
The principle
- High-level modules (business policy) should not depend on low-level modules (details: databases, frameworks, HTTP clients). Both should depend on abstractions.
- Abstractions should not depend on details; details should depend on abstractions.
The key word is inversion: in naive layered code, the source-code dependency points the same way as the flow of control (business logic calls and imports the database code). DIP introduces an interface owned by the high-level module, so the source dependency points from the detail to the policy, even though control still flows from policy to detail at runtime.
// Domain module owns the port; infrastructure implements it; wiring happens at the edge
// --- domain (no Spring, no JDBC imports) ---
public interface OrderRepository {
Optional<Order> find(OrderId id);
void save(Order order);
}
public final class PlaceOrder {
private final OrderRepository orders;
private final Clock clock;
public PlaceOrder(OrderRepository orders, Clock clock) { this.orders = orders; this.clock = clock; }
public OrderId handle(PlaceOrderCommand cmd) {
Order order = Order.place(cmd.customer(), cmd.items(), Instant.now(clock));
orders.save(order);
return order.id();
}
}
// --- infrastructure ---
@Repository
class JdbcOrderRepository implements OrderRepository { /* SQL here */ }
// --- configuration (composition root) ---
@Configuration
class Wiring {
@Bean PlaceOrder placeOrder(OrderRepository repo) { return new PlaceOrder(repo, Clock.systemUTC()); }
}
// Go: the consumer defines the interface it needs ("accept interfaces, return structs")
// package ordering (domain)
type Repository interface {
Find(ctx context.Context, id OrderID) (Order, error)
Save(ctx context.Context, o Order) error
}
type PlaceOrder struct {
Orders Repository
Now func() time.Time
}
// package postgres (infrastructure) — imports ordering, never the reverse
type OrderStore struct{ db *pgxpool.Pool }
func (s *OrderStore) Find(ctx context.Context, id ordering.OrderID) (ordering.Order, error) { /* ... */ }
func (s *OrderStore) Save(ctx context.Context, o ordering.Order) error { /* ... */ }
// main.go wires it: ordering.PlaceOrder{Orders: &postgres.OrderStore{db: pool}, Now: time.Now}
// Rust: generic over a trait (static dispatch) — the domain crate defines the trait
pub trait OrderRepository {
fn find(&self, id: OrderId) -> Result<Option<Order>, RepoError>;
fn save(&self, order: &Order) -> Result<(), RepoError>;
}
pub struct PlaceOrder<R: OrderRepository> { orders: R }
impl<R: OrderRepository> PlaceOrder<R> {
pub fn handle(&self, cmd: PlaceOrderCommand) -> Result<OrderId, PlaceOrderError> {
let order = Order::place(cmd)?;
self.orders.save(&order)?;
Ok(order.id)
}
}
// The postgres crate depends on the domain crate and implements OrderRepository for its type.
-- Haskell: abstract over capabilities with a type class (or pass a record of functions)
class Monad m => OrderRepo m where
findOrder :: OrderId -> m (Maybe Order)
saveOrder :: Order -> m ()
placeOrder :: OrderRepo m => PlaceOrderCmd -> m OrderId
placeOrder cmd = do
let order = mkOrder cmd
saveOrder order
pure (orderId order)
-- Production instance runs against Postgres in IO; tests use a pure State-based instance.
/* C: dependency inversion with a struct of function pointers (a hand-made vtable) */
typedef struct {
void *ctx;
int (*save)(void *ctx, const order *o);
int (*find)(void *ctx, order_id id, order *out);
} order_repo;
int place_order(const order_repo *repo, const place_order_cmd *cmd, order_id *out_id) {
order o;
if (order_init(&o, cmd) != 0) return -1;
if (repo->save(repo->ctx, &o) != 0) return -1;
*out_id = o.id;
return 0;
}
/* production passes a repo backed by SQLite; tests pass one backed by an array */
Dependency inversion vs dependency injection
- Dependency inversion is about the direction of source dependencies (policy owns abstractions).
- Dependency injection is a technique for supplying dependencies from outside (constructor parameters, frameworks), often used to implement DIP (chapter 137).
- Inversion of control is the broader idea that a framework calls your code (callbacks, event loops, DI containers).
When DIP hurts
- Interfaces for things that never vary and aren't boundaries (
StringUtilsinterfaces, an interface per class by default) add indirection without benefit. - Apply DIP at architectural boundaries (persistence, messaging, external services, time, randomness, frameworks) and where you need test seams; inside a cohesive module, concrete types are fine.
Composition over inheritance
The Gang of Four's advice: favour object composition over class inheritance. Inheritance couples subclasses to superclass internals (the fragile base class problem: a change in the base breaks subclasses), exposes protected implementation details, fixes relationships at compile time, and invites LSP violations. Composition (holding collaborators and delegating) keeps parts independent and swappable.
- Use inheritance for genuine is-a relationships with stable, well-designed base types (often abstract classes designed for extension), or for sealed hierarchies of variants.
- Prefer interfaces + composition for reusing behaviour.
- Languages reflect this: Go has no inheritance (embedding is composition with method promotion); Rust has no struct inheritance (traits + composition, default methods); Kotlin classes are
finalby default and support delegation (class LoggingRepo(inner: Repo) : Repo by inner); Java sealed classes control who may extend.
// Kotlin class delegation: decorate only what changes, delegate the rest automatically
interface OrderRepository { fun find(id: OrderId): Order?; fun save(order: Order) }
class AuditingOrderRepository(
private val inner: OrderRepository,
private val audit: AuditLog,
) : OrderRepository by inner {
override fun save(order: Order) {
inner.save(order)
audit.record("order.saved", order.id)
}
}
Companion principles
| Principle | Meaning | Caveat |
|---|---|---|
| DRY (Don't Repeat Yourself) | Every piece of knowledge has a single authoritative representation | About knowledge, not identical-looking code; wrong abstractions are costly |
| KISS | Prefer the simplest design that works | Simple ≠ easy; simple means few interacting parts |
| YAGNI | Don't build for speculative requirements | Still design seams at known boundaries |
| Law of Demeter | Talk only to immediate collaborators | Not about counting dots in fluent APIs |
| Tell, don't ask | Ask objects to do things rather than pulling their data and deciding outside | Balance with CQS and data-oriented code |
| GRASP (Craig Larman) | Patterns for assigning responsibilities: Information Expert, Creator, Controller, Low Coupling, High Cohesion, Polymorphism, Pure Fabrication, Indirection, Protected Variations | Protected Variations is the umbrella for OCP/DIP: identify points of predicted variation and create stable interfaces around them |
| Package principles (Martin) | Release-reuse equivalence, common closure, common reuse; acyclic dependencies, stable dependencies, stable abstractions | Apply at module/package scale (chapter 140) |
SOLID across paradigms: a summary
| Principle | OOP expression | Functional expression | Systems/procedural expression |
|---|---|---|---|
| SRP | Classes per actor/concern | Modules of functions per concern | Translation units/files per concern |
| OCP | Interfaces, plugins, decorators | Higher-order functions; sum types with exhaustive matching for operations | Function-pointer tables, registration |
| LSP | Behavioural subtyping, contract tests | Type class laws (Functor, Monoid laws), property tests | Implementations honouring header contracts |
| ISP | Role interfaces | Small type classes; functions taking minimal arguments/records | Narrow headers; opaque types |
| DIP | Ports owned by domain; DI | Pass functions/records of capabilities; tagless final, effect systems | Function pointers/vtables; link-time substitution |
Lab: Liskov, interface size and dependency inversion, measured
pytest 9.1 on the lab machine with five MenuStore implementations (memory, JSON file, PostgreSQL 16, and two "improved" subclasses), a 400-test service suite, and a scan of the Go 1.24.7 standard library source in /usr/local/go/src.
Experiment 1: contract tests across implementations
IMPLS = {"memory": MemoryStore, "file": lambda: FileStore(tempfile.mktemp()),
"uppercase": UpperCaseStore, "strict": StrictStore, "postgres": PgStore}
@pytest.fixture(params=IMPLS)
def store(request): return IMPLS[request.param]()
def test_get_returns_what_was_put(store): ...
def test_put_overwrites(store): ...
def test_missing_key_is_none(store): ...
FAILED test_get_returns_what_was_put[uppercase]
FAILED test_put_overwrites[uppercase]
FAILED test_missing_key_is_none[strict]
3 failed, 12 passed in 0.17s
The two failures are the two classic ways to break substitutability: changing the postcondition (UpperCase: what you get back isn't what you put) and strengthening a precondition or changing error behaviour (Strict: callers must now guarantee the key exists or handle a new exception). Python, Java and TypeScript type checkers accept both subclasses happily, since the method signatures match; only behavioural tests notice. In Java, the same pattern is an abstract JUnit test class extended once per implementation; Go uses a func testStore(t *testing.T, s Store) called from each implementation's test.
Experiment 2: how big are interfaces in a well-designed library?
| Measurement over Go's standard library (non-test, non-vendor source) | Count |
|---|---|
| exported interfaces | 221 |
| with exactly 1 method | 89 (40%) |
| with 2 / 3 / 4 / 5 / 6+ method lines | 67 / 25 / 15 / 5 / 19 |
concrete Read(p []byte) (n int, err error) methods |
≥ 43 |
concrete Write(p []byte) (n int, err error) methods |
≥ 36 |
functions taking an io.Reader parameter |
246 |
The counts are from regular expressions over source, so they're approximate: embedded interfaces count as "method lines", and the Read/Write patterns only match receivers written in the standard style. The proportions are the point: one-method interfaces dominate, and they are the ones with dozens of implementations and hundreds of users. Go's proverb "the bigger the interface, the weaker the abstraction" is ISP in seven words.
Experiment 3: dependency inversion and test cost
Store injected into MenuService |
400 tests |
|---|---|
MemoryStore |
0.31 s |
PgStore (real PostgreSQL over TCP) |
3.84 s |
The business logic (trim, reject empty, default special) is identical; only the plug-in changed. In a larger service, the difference is between a unit suite that runs on every save and one that needs a database container and minutes. The inversion also changes compile-time dependencies: the service module imports the abstraction, never psycopg, so a change to the database driver can't force the service to change or rebuild.
Experiment 4: single responsibility, seen in history
SRP is about reasons to change, which version control records. Run on a codebase of your own:
git log --format='%s' -- path/to/order_service.py | head -50
If the commit messages for one file mention pricing, emails, tax rules and database migrations, it answers to four stakeholders, and every one of their changes risks the others. Splitting along those lines is SRP; splitting a 50-line class into five 10-line classes with one reason to change between them isn't.
Try it yourself
- Write the
MenuStorecontract tests in Java (abstract JUnit class) or Go (shared helper) and run them against two implementations. - Make
StrictStoreLiskov-compliant by adding a separaterequire(key)method instead of changingget. - Find the largest interface in a codebase you work on, list which methods each caller actually uses, and sketch the split.
- Add a
RedisStoreand make it pass the contract tests unchanged.
Revision sheet: SOLID
Key ideas
- S: a module answers to one actor/stakeholder; separate code that changes for different reasons.
- O: design so common extensions are additions (new strategy, new handler), not edits.
- L: subtypes honour the base contract: no stronger preconditions, no weaker postconditions, same invariants and error behaviour; verify with contract tests.
- I: small, role-specific interfaces; let clients define the interfaces they need (Go's style).
- D: policy depends on abstractions owned by the policy layer; infrastructure implements them; wire at the edge (composition root).
- In functional code: S → small pure functions; O → higher-order functions; L → laws and contracts; I → minimal function signatures; D → passing functions/capabilities in.
- Costs: indirection, more types, speculative abstraction; apply where change actually happens.
Numbers to remember
- Lab: contract tests caught 2 of 5 implementations breaking the base contract.
- Lab: 40% of Go's 221 exported interfaces have one method; 246 functions take an
io.Reader. - Lab: injecting an in-memory store made 400 tests 12× faster.
Pitfalls
- Inheritance for code reuse that breaks substitutability.
- Interfaces mirroring a single class ("header interfaces") added "for testing" with no other use.
- God interfaces and god classes.
- Dependency injection containers used where plain constructor parameters suffice.
- Applying OCP to code that never gets extended.
Glossary
- Contract: preconditions, postconditions and invariants of an operation.
- Composition root: the one place where concrete implementations are wired together.
- Role interface: an interface defined by what one client needs.
- Strategy: interchangeable behaviour behind an interface (chapter 137).
- Speculative generality: abstraction for changes that never come.