Liskov Substitution Principle (LSP)
"If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T, the behavior of P is unchanged when o1 is substituted for o2, then S is a subtype of T." — Barbara Liskov, Data Abstraction and Hierarchy, OOPSLA '87 keynote
Summary: LSP says an implementation may stand in for its abstraction only if no caller written against the abstraction can tell the difference: it is the fine print of every interface. Focus: Subtype vs subclass, behavioral subtyping (preconditions, postconditions, invariants, the history constraint, exceptions, variance), the contracts of io.Reader and sort.Interface, fakes in tests, and API backward compatibility. Learning goal: Spot a substitution bug before it ships, state any interface's contract in four lines, and enforce it with types, final template methods and one contract test suite run against every implementation.
This page is the complete reference for the L in SOLID: where the rule comes from (Liskov 1987, Liskov & Wing 1994, Meyer's design by contract, Martin 1996), every part of a behavioural contract, how Go, PHP/Laravel, Java, C#, TypeScript and Python check (or fail to check) it, the classic violations and their fixes, and how the same rule becomes backward compatibility, Postel's law and consumer-driven contract tests once the "subtype" is a new version of a service. Its neighbours: Open–Closed explains why you program against abstractions at all; LSP is what makes that safe. Interface Segregation shrinks contracts so they are easier to honour, and Dependency Inversion decides who owns them. The SOLID overview is at /design/solid/.
Page map
| If you are looking for | Go to |
|---|---|
| The whole principle in tables | Everything in one minute |
| Why the rule exists and the trade-off | Why LSP exists |
| Liskov 1987, Liskov & Wing 1994, Meyer, Martin, Weirich | Where it comes from |
| Subtype vs subclass, pre/postconditions, invariants, history, exceptions, variance | The concepts, one by one |
io.Reader, sort.Interface, instanceof, Refused Bequest | Standard contracts and smells |
| What Go, PHP, Java, C#, TypeScript, Python check for you | Per-language behaviour |
| SQLite in tests vs PostgreSQL in production, and other "same interface" databases | Substituting infrastructure |
| Go and Laravel before/after code | Go, Laravel |
Compiler errors, final, @template, contract tests, runtime checks | Mechanics |
| Rectangle/Square, read-only collections, lying fakes, API evolution | Solving the classic problems |
| Which tool for which situation | Choosing an enforcement technique |
| Versions of services, Pact, Postel's law, replicas and caches | In architecture |
| Refactoring kata with real output | Lab |
| Wrong beliefs, cheat sheet, terms | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The contract parts. Every row is unpacked in the concepts section.
| Part of the contract | In plain words | Tiny example | A subtype may |
|---|---|---|---|
| Signature (types) | Names, parameter and return types | Read(p []byte) (int, error) | Accept wider parameters (contravariance), return narrower types (covariance) |
| Precondition | What the caller must guarantee | total >= 0 | Keep it or weaken it (accept more) |
| Postcondition | What the method guarantees on return | 0 <= discount <= total | Keep it or strengthen it (promise more) |
| Invariant | What is always true between calls | Rectangle: width and height are independent | Never break it |
| History constraint | How state may change over time | A bag's bound never changes; an immutable value stays immutable | Never allow a change the supertype forbids |
| Exceptions | Which failures callers must handle | Miss → ErrNotFound, not "", nil | Throw the same or fewer (or subtypes) |
| Performance / side effects (informal) | What callers silently rely on | Len() is O(1); Get does not write | Stay within what callers assumed, or document it |
The violations you will meet.
| Violation | Symptom in code | Fix |
|---|---|---|
| Rectangle/Square | A subclass that keeps an extra invariant breaks a setter's postcondition | Make values immutable, or drop the subtype relation |
| Refused Bequest | throw new NotImplementedException() / UnsupportedOperationException / empty method | Split the interface (ISP) or stop inheriting |
| Type check in the caller | instanceof, match (true), Go type switch on concrete types | Move the behaviour into the abstraction |
| Lying fake | Tests pass, production fails (fake returns null where real one throws) | Contract test suite run against fake and real |
| Breaking API change | New service version rejects requests old clients send | Expand and contract, consumer-driven contract tests |
| Caller assumes more than the contract | Code drops bytes returned with io.EOF | Read the documented contract; test with iotest |
The three things to do.
| Situation | Do this |
|---|---|
| Writing an interface | Write its contract in the doc comment: pre, post, invariants, errors |
| Writing an implementation or fake | Run the shared contract test suite against it |
| Changing a public API or event | Add, never remove or tighten; verify with consumer contracts before deploying |
Why LSP exists
Polymorphism lets one piece of code work with many implementations. That is only useful if the code does not need to know which implementation it got. The moment a caller must ask "is this the special one?", every new implementation becomes a change to every caller, and the abstraction stops paying for itself. LSP is the condition under which polymorphism is safe: a substitute must keep every promise the abstraction made.
| Weak contract (anything that compiles) | Strong contract (behavioural subtyping) |
|---|---|
| Any class that matches the signature is accepted | Only implementations that keep pre/post/invariants are accepted |
| Writing an implementation is fast | Writing an implementation needs the contract and its tests |
Callers defend themselves with type checks and null checks | Callers trust the abstraction |
| Bugs appear in production, far from the faulty class | Bugs fail the contract test next to the faulty class |
| Fakes drift from reality | Fakes are verified like real adapters |
The analogy we reuse on this page: a substitute teacher. The class is a program written against "teacher". A substitute is a valid subtype only if the school day proceeds without the students needing to know: same syllabus, same rules, same exam. A substitute who refuses to grade homework delivers less (weaker postcondition); one who requires every student to bring a laptop demands more (stronger precondition); one who rewrites the class rules for the rest of the term breaks the history. A substitute who also brings extra worksheets is fine: promising more is allowed.
Three common misunderstandings, up front
- "LSP is about inheritance." Liskov separated subtype (behaviour) from subclass (code reuse) in 1987. LSP applies to every interface implementation in Go, every PHP class implementing a contract, every fake in your test suite and every new version of an API.
- "If it compiles, it substitutes." A type checker sees signatures. Nothing in Go, PHP or Java checks that
Readreturns the bytes beforeio.EOFor that a discount never exceeds the total. Behaviour is checked by documentation, tests and runtime assertions. - "A subtype must behave identically." No: it may do more. A cache that also records metrics, a reader that returns more bytes per call, an API that adds fields: all valid. The rule is: demand no more, promise no less.
Where it comes from
Liskov, 1987. Barbara Liskov's OOPSLA '87 keynote, Data Abstraction and Hierarchy, was about data abstraction, not inheritance. In the section on type hierarchy she wrote that "the intuitive idea of a subtype is one whose objects provide all the behavior of objects of another type (the supertype) plus something extra", followed by the substitution property in the title quote. She also separated two notions the industry still blurs: subtype and supertype are semantic, about behaviour, while subclass and superclass are "simply linguistic concepts in programming languages". In Smalltalk, she noted, declaring a subclass is "simply a shorthand notation for building programs".
Liskov & Wing, 1994. A Behavioral Notion of Subtyping (ACM TOPLAS 16(6)) made the rule precise. The goal: the subtype relation "should ensure that any property proved about supertype objects also holds for its subtype objects." Their definition has three parts: signature rules (the standard contravariance of arguments, covariance of results, and an exception rule: a subtype method may not signal exceptions the supertype's caller does not expect), method rules (pre- and postconditions, "the intuitive counterparts to the contravariant and covariant rules for signatures"), and property rules: invariants plus a new history constraint (they call the formal version the constraint rule). Their example: "an invariant property of a bag is that its size is always less than its bound; a history property is that the bag's bound does not change."
Meyer, design by contract. Bertrand Meyer's Eiffel gave the same idea a language: require (precondition), ensure (postcondition), invariant, and rules for redefinition under inheritance. His introduction calls it subcontracting:
"a redefined version of r may keep or weaken the precondition; it may keep or strengthen the postcondition. Strengthening the precondition, or weakening the postcondition, would be a case of “dishonest subcontracting” and could lead to disaster." — Eiffel Software, Design by Contract: Introduction (eiffel.com)
Martin, 1996. Robert C. Martin's March 1996 C++ Report column named it the Liskov Substitution Principle and put it in C++ terms: "every function which operates upon a reference or pointer to a base class, should be able to operate upon derivatives of that base class without knowing it." His gloss: derived methods "must expect no more than the corresponding member functions of the base class; and should promise no less." He used Rectangle and Square as the example, and warned that a caller testing for the concrete type is the symptom.
Weirich, via Cheney. Dave Cheney's SOLID Go Design (2016) closes the Go reading of LSP with "this lovely aphorism from the late Jim Weirich": Require no more, promise no less.
The picture above is the whole principle: the supertype's contract on top, the two columns of what a subtype may and may not do below. Every concept block that follows unpacks one row.
The concepts, one by one
Each block follows the same order: plain words, the usual wrong belief, the definition, a call sequence showing the bug, real scenarios, how each language helps, and the fix.
Subtype vs subclass Must-know
In plain words: subclass is how code is reused (extends, embedding). Subtype is a promise that the new type can be used wherever the old one is expected. You can have either without the other.
Common misunderstanding: "class Square extends Rectangle makes Square a subtype." It makes it a subclass. Whether it is a subtype depends on behaviour, which the extends keyword does not check.
Definition: S is a (behavioural) subtype of T when every program written against T's specification keeps its correct behaviour when given an S. Subclassing is a language mechanism for sharing code; interface implementation (Go, PHP implements, Java implements) is a declaration of intent. Neither proves substitutability.
Caller (written against Rectangle) Object actually passed
1 r.SetWidth(5) Square: sets w=5, h=5
2 r.SetHeight(4) Square: sets w=4, h=4
3 assert r.Area() == 20 Square returns 16
4 -- subclass yes, subtype no: the caller's correct reasoning failsReal scenarios: ReadOnlyCollection extends Collection whose add throws; a CachedUserRepository extends UserRepository that returns stale data where the base promised fresh; an Eloquent model subclass that overrides save() to do nothing; Go types embedding another struct and "overriding" one method while the embedded methods still mutate the inner state.
| Language | Subclassing mechanism | Subtyping mechanism | Can they diverge? |
|---|---|---|---|
| Go | Struct embedding (promotion, not inheritance) | Implicit interface satisfaction | Yes: any type with the methods "implements", whatever it does |
| PHP / Laravel | extends, traits | implements, extends | Yes; traits copy code with no subtype relation at all |
| Java | extends | extends, implements | Yes |
| C# | : Base | : IInterface | Yes |
| TypeScript | extends | Structural typing: any shape match | Yes, and structural typing makes accidental "subtypes" common |
| Python | Class inheritance | Inheritance or typing.Protocol (structural) | Yes |
Fix: decide what the abstraction promises first, then decide whether a type keeps that promise. Reuse code by composition when it does not.
Behavioral subtyping and the signature rule (variance) Important
In plain words: the types in a method's signature can change in a subtype only in the safe direction: parameters may get wider (accept more), return types may get narrower (promise more).
Common misunderstanding: "Overriding with a more specific parameter type is a refinement." It is the opposite: a caller holding the supertype may pass the wider type, and the subtype would reject it. That is a stronger precondition expressed in types.
Definition: Contravariance of parameters: if T.m(Animal), then S.m may take Animal or any supertype of it. Covariance of return types: if T.m(): Animal, then S.m may return Animal or Dog. Liskov & Wing call these "the standard contra/covariance rules"; the exception rule is the same idea for thrown errors.
Caller holds a Feeder Runtime object
1 feeder.feed(new Cat()) DogFeeder::feed(Dog $d) -- narrower parameter
2 -- PHP: compile-time fatal "Declaration of DogFeeder::feed(Dog $d) must be compatible with Feeder::feed(Animal $a)"
3 -- TypeScript method syntax: accepted silently (method bivariance), crashes at run timeReal scenarios: a Repository::find(): ?Model overridden as find(): User (covariant, fine); an event handler interface handle(Event $e) implemented as handle(OrderPlaced $e) (contravariance violated); a generic Comparator<Animal> used where Comparator<Dog> is expected (contravariant generic, fine).
| Language | Parameter types in an override | Return types in an override | Generic variance |
|---|---|---|---|
| Go | Must match exactly; there is no override and no variance | Must match exactly | None (generics are invariant) |
| PHP 7.4+ | Contravariant allowed ("Contravariance allows a parameter type to be less specific") | Covariant allowed | Only in PHPDoc: PHPStan/Psalm @template-covariant |
| Java | Must match (a different type is an overload, not an override) | Covariant ("return-type-substitutable") | Use-site wildcards ? extends / ? super |
| C# | Must match | Covariant since C# 9 | out (covariant) / in (contravariant) on interfaces and delegates |
| TypeScript | Function types are contravariant under strictFunctionTypes; methods stay bivariant | Covariant | Structural; variance inferred, optional in/out annotations |
| Python (mypy) | Must be same or wider, else "incompatible with supertype" | Covariant | TypeVar(covariant=True) / contravariant=True |
Fix: let the type checker enforce what it can. In PHP rely on the engine's variance check; in TypeScript prefer function-typed properties over method syntax for callbacks if you want contravariance checked; in Go accept that signatures must match exactly and put behaviour in tests.
Preconditions Must-know
In plain words: what the caller must make true before calling. A substitute may ask for less, never for more.
Common misunderstanding: "Adding validation in a subclass is always safer." Validation that rejects inputs the base accepted is a stronger precondition: callers that were correct yesterday now fail.
Definition: a precondition is a predicate over the arguments and the object's state that must hold on entry. Rule: pre(T.m) ⇒ pre(S.m), so every call valid for T is valid for S.
Checkout (written against PaymentGateway) Implementation
1 gateway.charge(order with 0.50 EUR) StripeGateway: OK
2 gateway.charge(order with 0.50 EUR) NewGateway: throws "minimum 1.00 EUR"
3 -- caller never handled this; small orders fail after the provider switchReal scenarios: a new storage driver that rejects keys longer than 250 bytes (Memcached does; Redis does not); an SMS provider that rejects non-ASCII text; a repository that requires a transaction to be open; a queue driver with a smaller maximum message size than the one you replaced.
| Language / tool | How preconditions are expressed | Checked? |
|---|---|---|
| Eiffel | require | At run time, per assertion level |
| Go | Doc comment, explicit if + error return | Only by tests |
| PHP / Laravel | Types, assert(), explicit checks, form request validation at the edge | Types by the engine; the rest by tests |
| Java | Types, Objects.requireNonNull, Bean Validation | Types by the compiler |
| C# | Types, nullable reference types, guard clauses | Types and nullability by the compiler |
| TypeScript / Python | Types (structural), runtime validators (Zod, Pydantic) | Types statically, values at run time |
Fix: state the precondition in the abstraction's doc. If a new implementation genuinely needs a stronger one, the abstraction must change (and every caller with it), or the implementation must absorb the difference (split large messages, fall back for small amounts).
Postconditions Must-know
In plain words: what the method guarantees when it returns. A substitute may promise more, never less.
Common misunderstanding: "The return type is the postcondition." The type says int; the postcondition says 0 <= result <= total. Only the second keeps Checkout from charging a negative amount.
Definition: a postcondition relates the result and the final state to the inputs and the initial state (Eiffel's old). Rule: post(S.m) ⇒ post(T.m) whenever pre(T.m) held.
Checkout::pay(1000, $policy) DiscountPolicy implementation
1 $policy->apply(1000) PercentOff(10): 100 -- 0 <= 100 <= 1000
2 $policy->apply(1000) LoyaltyPoints(1500): 1500 -- breaks result <= total
3 return 1000 - 1500 -- -500: refund issued on a purchaseReal scenarios: a sorting function that returns a permutation but not a stable one where callers relied on stability; a repository whose save() returns before the write is durable (async replica) where the base guaranteed durability; a cache put that silently drops values over a size limit.
| What is promised | Usually expressed by | Enforced by |
|---|---|---|
| Range of a number | Doc comment | Template method that clamps or asserts |
| Non-null result | ?T vs T (PHP, C#, Kotlin), (T, error) (Go) | Compiler / engine |
| Durability, ordering, idempotency | Doc comment | Contract test against each implementation |
| Error kinds | Sentinel errors (Go), exception types (PHP, Java) | Contract test |
Fix: move the postcondition into code that every implementation runs through: a final template method in PHP (see Laravel), a wrapper function in Go, plus a contract test.
Invariants Must-know
In plain words: facts about an object that are true between any two calls. A subtype must keep the supertype's invariants and may add its own, as long as its own do not contradict what the supertype's methods promise.
Common misunderstanding: "Adding an invariant only makes a type safer." Square adds width == height. Rectangle's SetWidth promised that the height does not change. Both cannot hold, so the added invariant breaks an inherited postcondition.
Definition: a class invariant is a predicate over the object's state established by construction and preserved by every public method. Meyer: "Class invariants are consistency constraints characterizing the semantics of a class."
Stretch(r Resizable) in Go Object
1 r.SetWidth(5) *Rectangle{5, 0} *Square{5, 5}
2 r.SetHeight(4) *Rectangle{5, 4} *Square{4, 4}
3 return r.Area() 20 16Real scenarios: a SortedList subclass of List whose set(i, x) must break sort order or refuse; a Money subtype that allows negative amounts when the base guaranteed non-negative; a "read-only" user subtype whose email changes when the profile service syncs.
Fix: make values immutable (no setters means no setter postcondition to break), or do not relate the types at all. The Go after-snippet does both.
History constraint Important
In plain words: some promises are about how the object may change over time, not about one call. An immutable type must stay immutable in every subtype; a bounded bag's bound must never change.
Common misunderstanding: "If every method keeps the invariant, the subtype is fine." Liskov & Wing's point is that a subtype can add a method (say setBound) that keeps every invariant and still breaks callers who relied on the bound never changing.
Definition: for any two states of an object in one computation, where the first precedes the second, the history constraint (Liskov & Wing's constraint rule) must hold between them. Subtypes must satisfy the supertype's constraint, including through methods the supertype does not have.
Thread A (caches config) Thread B (has the subtype)
1 cfg := svc.Config() -- "immutable"
2 limit := cfg.MaxConn -- 100, cached in a pool
3 cfg.(*MutableConfig).SetMaxConn(10)
4 -- pool still sized for 100; A's reasoning ("Config never changes") is now falseReal scenarios: ImmutableMoney subclassed by MutableMoney; a PHP readonly DTO wrapped by a subclass exposing a setter on a copied property; an "append-only" ledger table whose repository subtype allows UPDATE; a Kafka topic with cleanup.policy=delete treated as if it were a compacted, never-forgetting log.
Fix: use language features that make history explicit: PHP 8.2 readonly classes, Go value types with unexported fields and no setters, Java records, C# record and init-only setters. Never subtype an immutable type with a mutable one.
Exceptions as part of the contract Must-know
In plain words: the failures a method can report are promises too. A substitute must report failures the same way, and must not introduce new kinds of failure that callers never prepared for.
Common misunderstanding: "Throwing is always safer than returning a wrong value." Throwing a new exception type where the caller expected a null or a sentinel error crashes a request that the base type would have handled.
Definition: Liskov & Wing's exception rule: the exceptions signalled by the subtype method must be contained in those of the supertype method. Java encodes part of it: an overriding method may not declare broader checked exceptions in its throws clause.
UserService (written against UserRepository) Implementation
1 $repo->find(42) -- contract: ?User, null on miss EloquentUserRepository: null
2 $repo->find(42) ApiUserRepository: throws RequestException (404)
3 -- the "user not found" page becomes HTTP 500 after switching repositoriesReal scenarios: a Go store returning "", nil instead of ErrNotFound (the lying fake in the lab); a Laravel cache store throwing BadMethodCallException('This cache store does not support locks.') when code calls Cache::lock() on a store that is not a LockProvider; a payment adapter that throws TimeoutException where the interface promised PaymentDeclined or success.
| Language | How the error contract is expressed | What the compiler checks |
|---|---|---|
| Go | Sentinel errors (io.EOF, sql.ErrNoRows), errors.Is/errors.As, doc comments | Nothing beyond the error type |
| PHP | @throws PHPDoc, exception hierarchy | Nothing (PHPStan can check @throws with configuration) |
| Java | Checked exceptions in throws | Overrides may not widen checked exceptions |
| C# | XML doc <exception> | Nothing |
| TypeScript / Python | Docs | Nothing |
Fix: translate infrastructure errors into the abstraction's errors at the adapter boundary (404 → null, driver error → ErrNotFound), and assert error behaviour in the contract test.
Standard contracts and smells
io.Reader: a contract the compiler cannot see Must-know
In plain words: the one method Read(p []byte) (n int, err error) comes with a page of rules; types and callers that ignore them compile and misbehave.
Common misunderstanding: "If err != nil, n is zero." The documentation says the opposite is allowed:
"When Read encounters an error or end-of-file condition after successfully reading n > 0 bytes, it returns the number of bytes read. It may return the (non-nil) error from the same call or return the error (and n == 0) from a subsequent call." — Go standard library,
io.Readerdocumentation (io.go)
Definition: the contract also says implementations "are discouraged from returning a zero byte count with a nil error", that callers "should treat a return of 0 and nil as indicating that nothing happened", and "Implementations must not retain p." LSP binds both sides: an implementation must keep these rules, and a caller must not assume more than they promise.
NaiveCount (caller) iotest.DataErrReader("hello world")
1 Read(buf[4]) -> 4, nil total=4
2 Read(buf[4]) -> 4, nil total=8
3 Read(buf[4]) -> 3, io.EOF returns 8 -- the 3 bytes delivered with EOF are dropped
4 CorrectCount adds n first, then checks err -> 11Real scenarios: a decompressor that returns the last block together with io.EOF; a network reader that returns 0, nil in a loop and makes io.Copy spin; a wrapper that keeps a reference to p and corrupts the next read.
Fix: handle n > 0 before err; test readers with testing/iotest.TestReader and callers with iotest.DataErrReader, iotest.OneByteReader, iotest.HalfReader, iotest.TimeoutReader. Code in Go.
sort.Interface and strict weak ordering Important
In plain words: Less must behave like a real "less than": consistent and transitive. A Less that compiles but is not an ordering makes sort.Sort return garbage, silently.
Common misunderstanding: "a < b is always a valid Less." For floats it is not: the sort package documents that "floating-point comparison (the < operator on float32 or float64 values) is not a strict weak ordering when not-a-number (NaN) values are involved."
Definition: the doc comment on Less says it "must describe a Strict Weak Ordering", with examples: "if both Less(i, j) and Less(j, k) are true, then Less(i, k) must be true as well", and the same for false.
Input: [3 NaN 1 2 NaN 0]
1 sort.Slice(xs, func(i, j int) bool { return xs[i] < xs[j] }) -> [3 NaN 1 2 NaN 0] (unchanged: NaN poisons every comparison)
2 sort.Float64s(ys) -> [NaN NaN 0 1 2 3] (Float64Slice.Less orders NaN first)Real scenarios: a comparator that uses <= instead of < (not irreflexive); a comparator over mutable fields that change during the sort; a multi-key comparator that compares the second key even when the first differs; PHP usort callbacks returning bool instead of -1/0/1 (deprecated since PHP 8 and wrong for equal elements).
Fix: use cmp.Compare (Go 1.21+, orders NaN consistently) with slices.SortFunc, or Float64Slice.Less; in PHP use the spaceship operator <=>.
Refused Bequest, NotImplementedException and type checks Must-know
In plain words: when a subclass does not want some inherited behaviour, it throws, does nothing, or callers start asking "which type is this?". All three are LSP violations wearing a disguise.
Common misunderstanding: "Throwing NotImplementedException is honest." It is honest about the implementation and dishonest about the type: the class claims to be a T and then refuses part of T.
Definition: Refused Bequest is the code smell (Fowler and Beck, Refactoring; see the code smells chapter, /design/code-smells) where "a subclass uses only some of the methods and properties inherited from its parents". The caller-side symptom Martin described in 1996 is the type check: if ($shape instanceof Square), a Go type switch on concrete types, or a match (true) on ::class.
Caller What it must now do
1 foreach ($channels as $c) $c->sendEmail(...) SmsChannel throws LogicException
2 if (! $c instanceof SmsChannel) $c->sendEmail() caller learns about every subtype
3 -- each new channel = edit every caller (OCP broken because LSP was broken)Real scenarios: Java's Collections.unmodifiableList throws UnsupportedOperationException from add (the JDK documents these as "optional operations"); .NET's ReadOnlyCollection<T> throws NotSupportedException from ICollection<T>.Add; the Laravel cache Repository::lock() check instanceof LockProvider that throws BadMethodCallException; a Go handler doing switch s := store.(type) { case *RedisStore: ... }.
| Signal | What it usually means | Refactoring |
|---|---|---|
Empty override / return null | Subclass refuses behaviour | Replace inheritance with delegation; split the interface |
throw new NotImplementedException / UnsupportedOperationException / LogicException | Interface is too fat for this implementation | ISP: one interface per client need |
instanceof / type switch on concrete types | Behaviour lives in the caller | Move it into a method on the abstraction (polymorphism) |
Type switch on optional interfaces (if rf, ok := fsys.(fs.ReadFileFS)) | Deliberate capability check | Fine when the base contract is complete without it |
Fix: split the interface so each implementation can honour all of it, or check for an optional capability interface whose absence is part of the documented contract (Go's fs.ReadFileFS, Laravel's LockProvider), never for a concrete class.
Substitutability in tests: fakes that honour contracts Must-know
In plain words: a fake, stub or in-memory implementation is a subtype too. If it behaves differently from the real thing, your green tests predict nothing.
Common misunderstanding: "Mocks are just for tests; they do not need to be correct." Every assertion you make with a fake assumes the fake behaves like production. A fake that returns null where the real adapter throws hides the exact bug you wanted the test to find.
Definition: a contract test is one test suite written against the abstraction and executed against every implementation: real adapters (against a real PostgreSQL or Redis in CI) and the fakes used by unit tests. Passing it is the operational meaning of "is a subtype".
contract.Run(t, newStore) MemStore LyingStore
1 Get("absent") ErrNotFound "", nil -> FAIL
2 Put("k","v1"); Get("k") "v1" "v1"
3 Put twice; Get "v2" "v2"The diagram shows the shape: one suite on top, every implementation underneath, and the same idea stretched across a network as consumer-driven contracts.
Real scenarios: Laravel's array cache store swapped in for Redis (CACHE_STORE=array in phpunit.xml), Queue::fake(), Mail::fake(), Storage::fake(); Go httptest.Server standing in for a remote API; an in-memory repository for domain tests; SQLite :memory: standing in for PostgreSQL (see Substituting infrastructure).
Fix: write contract.Run once (Go code in Go); in PHPUnit, an abstract StoreContractTest with an abstract makeStore() method, extended once per implementation.
API backward compatibility and Postel's law Important
In plain words: version 2 of a service is a substitute for version 1. Every client written against v1 is a "program P defined in terms of T". If any of them breaks, v2 is not a subtype.
Common misunderstanding: "We only added a validation rule, that's not a breaking change." Rejecting input v1 accepted is a stronger precondition: it breaks clients exactly as Square breaks Stretch.
Definition: the Liskov & Wing rules map directly onto APIs: accept everything v1 accepted (preconditions), return everything v1 returned, with the same meaning (postconditions), keep identifiers and semantics stable (invariants and history), and do not add new error responses clients cannot handle (exceptions). The networking version is the robustness principle, Postel's law:
"TCP implementations should follow a general principle of robustness: be conservative in what you do, be liberal in what you accept from others." — RFC 761, DoD Standard Transmission Control Protocol, section 2.10, January 1980
RFC 1122 (1989) repeats it as "Be liberal in what you accept, and conservative in what you send". Being liberal has a cost that Hyrum's law (an observation popularised by Hyrum Wright; secondary source) names: with enough users, every observable behaviour, including accidental leniency, becomes something someone depends on.
Mobile app v3.2 (in the field) API
1 POST /orders {"qty": "2"} v1: accepts string, coerces -> 201
2 POST /orders {"qty": "2"} v2: strict int validation -> 422
3 -- app store review takes 3 days; orders fail until users updateReal scenarios: removing a JSON field a client parses; renaming an enum value; changing an event's meaning without changing its name; tightening a database column from nullable to NOT NULL while old writers still send NULL (the expand and contract pattern exists for this).
Fix: add, never remove or tighten, within a version; deprecate with a timeline; run consumer-driven contract tests (Pact) in the provider's CI; for database schemas use expand and contract (SQL in Solving the classic problems).
Per-language behaviour
What the toolchain checks for you.
| Check | Go | PHP / Laravel | Java | C# | TypeScript | Python |
|---|---|---|---|---|---|---|
| Method exists with right name | Yes (implicit interfaces) | Yes (implements) | Yes | Yes | Yes (structural) | Only with mypy/pyright (Protocol, ABC) |
| Parameter variance | Exact match only | Contravariant (7.4+) | Exact (else overload) | Exact | Bivariant for methods; contravariant for function types with strictFunctionTypes | Contravariant (mypy) |
| Return variance | Exact match only | Covariant (7.4+) | Covariant | Covariant (C# 9+) | Covariant | Covariant |
| Exceptions | No | No (PHPStan optional) | Checked exceptions cannot widen | No | No | No |
| Prevent override | No inheritance to override | final method / class | final | sealed | No (convention, #private) | @final (typing, checked by mypy) |
| Generic variance | None | PHPDoc @template-covariant (PHPStan, Psalm) | Wildcards | in / out | Inferred, in/out | TypeVar(covariant=...) |
| Behaviour (pre/post/invariant) | Tests, iotest, fstest | Tests, assert() | Tests, assertions | Tests, Debug.Assert | Tests | Tests, assert |
What each framework relies on.
| Framework | Substitution it depends on | Where the contract lives |
|---|---|---|
| Go stdlib | Every io.Reader, io.Writer, http.Handler, sql/driver.Driver, fs.FS | Doc comments; testing/iotest, testing/fstest |
| Laravel 13 | Every driver behind Illuminate\Contracts\* (cache, queue, mail, filesystem, session) | Contracts + framework test suite; fakes in Illuminate\Support\Testing\Fakes |
| Spring | Beans injected by interface; profiles swap implementations | Javadoc; your tests |
| ASP.NET Core | IServiceCollection registrations swapped per environment | XML doc; your tests |
| NestJS | Providers swapped with useClass / useValue in tests | TypeScript types; your tests |
| Django / FastAPI | Database backends, cache backends, dependency overrides | Docs; backend test suites |
Substituting infrastructure: the database is a subtype too Important
Swapping one database, cache or queue for another "compatible" one is a substitution, and LSP predicts exactly where it breaks: wherever callers relied on behaviour the substitute does not have.
| Substitution | Looks compatible because | Breaks where |
|---|---|---|
SQLite :memory: for PostgreSQL in tests | Laravel and GORM speak both | SQLite has no SELECT ... FOR UPDATE; type affinity accepts 'abc' in an INTEGER column (non-STRICT tables); no ILIKE, no jsonb operators |
| MySQL for PostgreSQL | Same SQL standard | Default InnoDB collations are case-insensitive ('A' = 'a' in a unique index); GROUP BY and empty-string handling differ |
| Oracle for PostgreSQL | Same SQL standard | Oracle treats the empty string '' as NULL |
| SQL Server for PostgreSQL | Same SQL standard | Default Read Committed is locking, not MVCC, unless RCSI is on |
| CockroachDB for PostgreSQL | PostgreSQL wire protocol | Default isolation is Serializable: code that never retried 40001 now must |
| Redis cache for the array cache store | Same Illuminate\Contracts\Cache\Repository | The array store lives for one process; TTLs and eviction differ |
| MongoDB driver for an SQL repository | Same repository interface | Multi-document atomicity needs explicit transactions on a replica set |
The fix is the same as for fakes: one contract test suite, run in CI against the real engine through containers, and an adapter that translates engine differences into the abstraction's terms. Engine behaviour is the subject of Isolation Levels.
-- The same statement, three engines: a substitution test you can run in CI.
CREATE TABLE users (id integer PRIMARY KEY, email varchar(255) UNIQUE);
INSERT INTO users VALUES (1, 'Ann@example.com');
INSERT INTO users VALUES (2, 'ann@example.com');
-- PostgreSQL: succeeds (case-sensitive text comparison)
-- MySQL 8 InnoDB, default utf8mb4_0900_ai_ci: ERROR 1062 (23000): Duplicate entry
-- SQLite: succeeds (BINARY collation by default)Go
Before
Go has no inheritance, but embedding plus an interface reproduces the problem faithfully. Stretch is correct for every Rectangle and silently wrong for a Square.
package before
type Resizable interface {
SetWidth(w float64)
SetHeight(h float64)
Area() float64
}
type Rectangle struct{ W, H float64 }
func (r *Rectangle) SetWidth(w float64) { r.W = w }
func (r *Rectangle) SetHeight(h float64) { r.H = h }
func (r *Rectangle) Area() float64 { return r.W * r.H }
// Square "is a" Rectangle, so we embed it and keep the sides equal.
type Square struct{ Rectangle }
func (s *Square) SetWidth(w float64) { s.W, s.H = w, w }
func (s *Square) SetHeight(h float64) { s.W, s.H = h, h }
// Stretch was written against Resizable and is correct for every Rectangle.
// Hand it a Square and the assertion that callers rely on (area == 5 * 4) is false.
func Stretch(r Resizable) float64 {
r.SetWidth(5)
r.SetHeight(4)
return r.Area() // a Square returns 16, not 20
}After
Fix the contract, not the square. Shape promises only what every shape can honour, and resizing becomes a value-producing operation on the concrete type, so there is no mutating postcondition to break and no history to violate.
package after
// Shape promises only what every shape can honour.
// There is no mutating contract to break.
type Shape interface {
Area() float64
}
type Rectangle struct{ W, H float64 }
func (r Rectangle) Area() float64 { return r.W * r.H }
type Square struct{ Side float64 }
func (s Square) Area() float64 { return s.Side * s.Side }
// Resizing is an operation that produces a new value, and it belongs
// to the concrete type whose invariants it understands.
func (r Rectangle) Resized(w, h float64) Rectangle { return Rectangle{W: w, H: h} }
func (s Square) Resized(side float64) Square { return Square{Side: side} }
// TotalArea works for any mix of shapes, and no shape can surprise it.
func TotalArea(shapes ...Shape) float64 {
var sum float64
for _, s := range shapes {
sum += s.Area()
}
return sum
}A caller that assumes too much
LSP binds callers as well. NaiveCount assumes a stronger postcondition than io.Reader promises; Upper is a decorator that keeps the contract byte for byte.
// Package reader shows that LSP binds callers too: a caller that assumes a
// stronger postcondition than io.Reader documents is as wrong as a reader
// that breaks the contract.
package reader
import (
"errors"
"io"
)
// NaiveCount assumes "n > 0 implies err == nil". io.Reader never promised
// that, so the bytes delivered together with io.EOF are silently dropped.
func NaiveCount(r io.Reader) (int, error) {
buf := make([]byte, 4)
total := 0
for {
n, err := r.Read(buf)
if errors.Is(err, io.EOF) {
return total, nil
}
if err != nil {
return total, err
}
total += n
}
}
// CorrectCount follows the documented contract: process the n > 0 bytes
// first, then look at the error.
func CorrectCount(r io.Reader) (int, error) {
buf := make([]byte, 4)
total := 0
for {
n, err := r.Read(buf)
total += n
if errors.Is(err, io.EOF) {
return total, nil
}
if err != nil {
return total, err
}
}
}
// Upper is a well-behaved io.Reader decorator: it returns exactly what the
// wrapped reader returns, byte for byte and error for error.
type Upper struct{ R io.Reader }
func (u Upper) Read(p []byte) (int, error) {
n, err := u.R.Read(p)
for i := 0; i < n; i++ {
if 'a' <= p[i] && p[i] <= 'z' {
p[i] -= 'a' - 'A'
}
}
return n, err
}testing/iotest turns the documented contract into executable checks:
package reader
import (
"strings"
"testing"
"testing/iotest"
)
// iotest.TestReader checks the documented io.Reader contract
// (short reads, EOF handling, ReadAt/Seek if present) against the
// content the reader is supposed to produce.
func TestUpperHonoursReaderContract(t *testing.T) {
r := Upper{R: strings.NewReader("hello, reader")}
if err := iotest.TestReader(r, []byte("HELLO, READER")); err != nil {
t.Fatal(err)
}
}
func TestCountersAgainstDataErrReader(t *testing.T) {
// DataErrReader returns the final bytes together with io.EOF:
// legal under the io.Reader contract.
const s = "hello world"
if n, _ := CorrectCount(iotest.DataErrReader(strings.NewReader(s))); n != len(s) {
t.Fatalf("CorrectCount = %d, want %d", n, len(s))
}
}One contract suite, every implementation
The contract is a function that takes a constructor. The PostgreSQL adapter's test, the Redis adapter's test and the fake's test all call it.
// Package contract shows a contract test: one suite, written against the
// abstraction, run against every implementation (real adapters and fakes).
package contract
import (
"context"
"errors"
"sync"
"testing"
)
// ErrNotFound is part of the contract: a miss is reported with this error,
// never with an empty string and a nil error.
var ErrNotFound = errors.New("not found")
// Store is the abstraction the application owns.
type Store interface {
Get(ctx context.Context, key string) (string, error)
Put(ctx context.Context, key, value string) error
}
// Run is the behavioural contract of Store. Every implementation's test
// file calls it: the PostgreSQL adapter, the Redis adapter, the fake.
func Run(t *testing.T, newStore func(t *testing.T) Store) {
ctx := context.Background()
t.Run("miss returns ErrNotFound", func(t *testing.T) {
s := newStore(t)
if _, err := s.Get(ctx, "absent"); !errors.Is(err, ErrNotFound) {
t.Fatalf("Get(absent) error = %v, want ErrNotFound", err)
}
})
t.Run("put then get returns the value", func(t *testing.T) {
s := newStore(t)
if err := s.Put(ctx, "k", "v1"); err != nil {
t.Fatal(err)
}
if got, err := s.Get(ctx, "k"); err != nil || got != "v1" {
t.Fatalf("Get(k) = %q, %v; want v1, nil", got, err)
}
})
t.Run("last write wins", func(t *testing.T) {
s := newStore(t)
_ = s.Put(ctx, "k", "v1")
_ = s.Put(ctx, "k", "v2")
if got, _ := s.Get(ctx, "k"); got != "v2" {
t.Fatalf("Get(k) = %q, want v2", got)
}
})
}
// MemStore is a fake that honours the contract, so tests that use it
// predict production behaviour.
type MemStore struct {
mu sync.Mutex
m map[string]string
}
func NewMemStore() *MemStore { return &MemStore{m: map[string]string{}} }
func (s *MemStore) Get(_ context.Context, key string) (string, error) {
s.mu.Lock()
defer s.mu.Unlock()
v, ok := s.m[key]
if !ok {
return "", ErrNotFound
}
return v, nil
}
func (s *MemStore) Put(_ context.Context, key, value string) error {
s.mu.Lock()
defer s.mu.Unlock()
s.m[key] = value
return nil
}
// LyingStore compiles as a Store but reports a miss as "", nil.
// Callers that branch on ErrNotFound will treat absent keys as empty values.
type LyingStore struct{ MemStore }
func NewLyingStore() *LyingStore { return &LyingStore{MemStore{m: map[string]string{}}} }
func (s *LyingStore) Get(ctx context.Context, key string) (string, error) {
v, err := s.MemStore.Get(ctx, key)
if errors.Is(err, ErrNotFound) {
return "", nil
}
return v, err
}package contract
import "testing"
func TestMemStoreContract(t *testing.T) {
Run(t, func(*testing.T) Store { return NewMemStore() })
}
// Kata step: uncomment to watch the contract catch the lying fake.
// func TestLyingStoreContract(t *testing.T) {
// Run(t, func(*testing.T) Store { return NewLyingStore() })
// }A real adapter's test calls the same suite against a container, skipping when no database is configured:
func TestPostgresStoreContract(t *testing.T) {
dsn := os.Getenv("TEST_DATABASE_URL")
if dsn == "" {
t.Skip("TEST_DATABASE_URL not set")
}
contract.Run(t, func(t *testing.T) contract.Store {
db := mustOpen(t, dsn) // pgx stdlib, truncates the table in t.Cleanup
return postgres.NewStore(db)
})
}The Go angle
Go interfaces are satisfied implicitly, so the compiler checks method sets and nothing else; there is no override, no variance and no final. That makes the documented contract and its tests the only enforcement, and the standard library is unusually careful about both: io.Reader's rules, sort.Interface's strict weak ordering, fs.FS's note that "[testing/fstest.TestFS] may be used to test implementations of an FS for correctness". Cheney's summary of why small interfaces help LSP: "By defining small interfaces, we can be more confident that implementations will faithfully satisfy their contract." Two Go-specific traps: embedding promotes methods you may not want (a struct embedding *sql.DB exposes Exec to every caller), and a type switch on concrete types in a caller is the Go spelling of instanceof. A type assertion to an optional interface (io.WriterTo, fs.ReadFileFS, http.Flusher) is the accepted exception: the base contract must be complete without it.
Laravel
Before
A DiscountPolicy interface whose documented contract is "return a non-negative amount, never larger than the total". The engine enforces the signature; nothing enforces the promise. LoyaltyPoints compiles and breaks Checkout.
<?php
namespace App\Pricing;
// The contract, in words: apply() returns a non-negative amount
// that is never larger than $totalCents.
interface DiscountPolicy
{
public function apply(int $totalCents): int;
}
final class PercentOff implements DiscountPolicy
{
public function __construct(private int $percent) {}
public function apply(int $totalCents): int
{
return intdiv($totalCents * $this->percent, 100);
}
}
// Looks like a DiscountPolicy, compiles like a DiscountPolicy,
// but it breaks the promise: a loyal customer with a big balance
// can receive a discount larger than the order itself.
final class LoyaltyPoints implements DiscountPolicy
{
public function __construct(private int $pointsCents) {}
public function apply(int $totalCents): int
{
return $this->pointsCents; // may exceed $totalCents
}
}
// Written against the interface, correct for PercentOff, wrong for LoyaltyPoints.
final class Checkout
{
public function pay(int $totalCents, DiscountPolicy $policy): int
{
return $totalCents - $policy->apply($totalCents); // can go negative
}
}After
Move the promise into code. An abstract base with a final Template Method guarantees the precondition and postcondition for every present and future subclass; subclasses only supply the raw amount. Checkout is unchanged and now safe.
<?php
namespace App\Pricing;
use InvalidArgumentException;
// The contract is now enforced, not merely described.
// Subclasses supply the rate; the base class guarantees the postcondition.
abstract class DiscountPolicy
{
final public function apply(int $totalCents): int
{
if ($totalCents < 0) {
throw new InvalidArgumentException('Total cannot be negative.');
}
$amount = $this->amountFor($totalCents);
return max(0, min($amount, $totalCents));
}
/** May return any integer; apply() clamps it to the contract. */
abstract protected function amountFor(int $totalCents): int;
}
final class PercentOff extends DiscountPolicy
{
public function __construct(private int $percent) {}
protected function amountFor(int $totalCents): int
{
return intdiv($totalCents * $this->percent, 100);
}
}
final class LoyaltyPoints extends DiscountPolicy
{
public function __construct(private int $pointsCents) {}
protected function amountFor(int $totalCents): int
{
return $this->pointsCents; // clamped by apply(), so the promise holds
}
}
// Unchanged, and now safe for every present and future policy.
final class Checkout
{
public function pay(int $totalCents, DiscountPolicy $policy): int
{
return $totalCents - $policy->apply($totalCents);
}
}A contract test in PHPUnit
<?php
namespace Tests\Contracts;
use App\Contracts\IdempotencyStore;
use PHPUnit\Framework\TestCase;
// One abstract suite. Each implementation's test extends it and supplies makeStore().
abstract class IdempotencyStoreContract extends TestCase
{
abstract protected function makeStore(): IdempotencyStore;
public function test_first_claim_wins_and_second_is_refused(): void
{
$store = $this->makeStore();
$this->assertTrue($store->claim('order-42'));
$this->assertFalse($store->claim('order-42'));
}
public function test_unknown_key_is_not_claimed(): void
{
$this->assertFalse($this->makeStore()->isClaimed('never-seen'));
}
}
// tests/Contracts/RedisIdempotencyStoreTest.php (runs against Redis in CI)
final class RedisIdempotencyStoreTest extends IdempotencyStoreContract
{
protected function makeStore(): IdempotencyStore
{
return new \App\Idempotency\CacheIdempotencyStore(cache()->store('redis'));
}
}
// tests/Contracts/ArrayIdempotencyStoreTest.php (the fake used by unit tests)
final class ArrayIdempotencyStoreTest extends IdempotencyStoreContract
{
protected function makeStore(): IdempotencyStore
{
return new \App\Idempotency\CacheIdempotencyStore(cache()->store('array'));
}
}(The Redis variant needs the Laravel application booted, so in a real project these extend Tests\TestCase; the shape is what matters.)
Generics in PHPDoc: @template
PHP has no generics, but PHPStan and Psalm read @template and @template-covariant, which lets a collection or repository state its variance:
<?php
/**
* @template-covariant T of \App\Models\Model
*/
interface ReadRepository
{
/** @return T|null */
public function find(int $id): ?\App\Models\Model;
}
/** @implements ReadRepository<\App\Models\User> */
final class UserRepository implements ReadRepository
{
public function find(int $id): ?\App\Models\User // covariant return, allowed since PHP 7.4
{
return \App\Models\User::find($id);
}
}The Laravel angle
Laravel's test tooling is LSP in daily use. CACHE_STORE=array, QUEUE_CONNECTION=sync, MAIL_MAILER=array, Queue::fake(), Mail::fake(), Storage::fake() and swapping a binding with $this->app->instance(PaymentGateway::class, $fake) all substitute one implementation of an Illuminate\Contracts interface for another and trust that the application cannot tell. Where a capability is genuinely optional, the framework uses a separate interface rather than lying: Illuminate\Contracts\Cache\LockProvider is implemented by the Redis, Memcached, DynamoDB, database, file and array stores, and Cache\Repository::lock() checks instanceof LockProvider and throws BadMethodCallException('This cache store does not support locks.') otherwise. That is the right shape: the base Store contract is complete, locks are an opt-in role. The common application-level violations are an Eloquent model subclass that overrides save() to do nothing, a repository that throws on a miss where the interface promises null, and a fake gateway that never declines a card.
Mechanics
What the engine says when variance is violated Important
| Language | Violation | What you get |
|---|---|---|
| PHP 8 | Narrower parameter or wider return in an override | Fatal error at class load: Declaration of Child::m(...) must be compatible with Parent::m(...) |
| PHP 8 | Overriding a final method | Fatal error: Cannot override final method Parent::m() |
| Java | Override declares a broader checked exception | Compile error: overridden method does not throw that exception |
| mypy | Narrower parameter | Argument 1 of "f" is incompatible with supertype "Base" (paraphrase: mypy also prints a note pointing to the Liskov substitution principle) |
| TypeScript | Narrower method parameter | No error (method bivariance); function-typed property: error under strictFunctionTypes |
| Go | Different signature | The type simply does not satisfy the interface: does not implement X (wrong type for method M) |
Making the contract executable Must-know
Ranked from cheapest to strongest:
- Write it down. Four lines in the interface's doc comment: precondition, postcondition, invariant, errors.
- Types. Non-nullable returns, value objects (
Money,NonNegativeInt), enums instead of strings. A type that cannot represent the illegal value removes the rule. - Template Method with
final. The base class owns the public method, checks pre/postconditions, and delegates to a protected hook (amountFor()). Subclasses cannot skip the checks. - Decorator that asserts. In Go, wrap any implementation in a checking decorator in tests (
type checkedStore struct{ Store }that verifies postconditions on each call). - Contract test suite. One suite, every implementation, run in CI.
- Consumer-driven contracts. Across processes: Pact records consumer expectations and the provider verifies them before deploying.
Template Method and final as contract enforcement Important
Checkout DiscountPolicy::apply() [final] LoyaltyPoints::amountFor()
1 $p->apply(1000) ─▶ check pre: total >= 0
2 $amount = $this->amountFor(1000) ─▶ return 1500
3 return max(0, min(1500, 1000)) -- post: 0 <= 1000 <= 1000
4 1000 - 1000 = 0 ◀─ -- the subclass could not weaken the postconditionPHP's manual: "The final keyword prevents child classes from overriding a method, property, or constant". Mark the public, contract-bearing method final and leave only the hook open. In Laravel apps, make concrete classes final by default (the existing snippets do), and open them deliberately.
Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| Rectangle/Square | Immutable values, no subtype relation | Shape{Area()}; Resized() returns a new value | No setter postcondition to break | Callers that mutated in place must reassign |
| Read-only collection | Separate read and write interfaces | ReadableList + MutableList (ISP) | No UnsupportedOperationException | More interfaces |
| Lying fake | Contract test suite | Same suite for fake and real | Fakes predict production | Needs real infrastructure in CI |
| Subclass weakens postcondition | final Template Method | Base checks, hook computes | Enforced for future subclasses | Inheritance stays; prefer composition otherwise |
| Caller type-checks | Move behaviour into the abstraction | New method on the interface, or a visitor | New types need no caller edits | Interface grows; check ISP |
| Optional capability | Optional interface | fs.ReadFileFS, LockProvider, http.Flusher | Base contract stays honest | Callers need a fallback path |
| Breaking API change | Expand and contract + Pact | Add, migrate consumers, then remove | Zero-downtime evolution | Two versions live for a while |
| Database differences | Adapter translates; contract tests on the real engine | Testcontainers in CI | Catches collation, locking, NULL differences | Slower test suite |
API evolution without breaking substitutability
The database version of the same rule: old application code is a program written against schema v1. The new schema must accept everything it does until the code is gone.
-- Expand: v2 schema accepts everything v1 writers send.
ALTER TABLE orders ADD COLUMN currency char(3) NULL; -- new, optional
UPDATE orders SET currency = 'EUR' WHERE currency IS NULL; -- backfill (in batches)
-- Deploy code that writes currency. Wait until no v1 writer remains.
-- Contract: only now tighten the precondition.
ALTER TABLE orders ALTER COLUMN currency SET NOT NULL; -- PostgreSQL
-- MySQL: ALTER TABLE orders MODIFY currency char(3) NOT NULL;The same order applies to JSON APIs and events: add the field (optional), migrate every consumer, verify with their contracts, then make it required or remove the old one. Event evolution is covered in Message Design & Schema Evolution.
Consumer-driven contracts with Pact
Pact's documentation defines the technique: "Contract testing is a technique for testing an integration point by checking each application in isolation to ensure the messages it sends or receives conform to a shared understanding that is documented in a 'contract'." In practice:
1 Consumer CI: unit tests run against a Pact mock provider -> pact file (requests + minimal expected responses)
2 Pact Broker stores the pact, tagged with the consumer version deployed to production
3 Provider CI: replays every consumer's pact against the real provider -> pass/fail per consumer
4 can-i-deploy: provider version X is deployable only if it satisfies every pact in productionThat is Liskov's "for all programs P defined in terms of T", restricted to the programs that actually exist.
Choosing an enforcement technique
| Situation | Recommended | Extra technique | Reason |
|---|---|---|---|
| Interface with several adapters (DB, cache, payment) | Contract test suite | Testcontainers for real engines | Only tests check behaviour |
| Base class with invariants subclasses must keep | final Template Method | final concrete classes elsewhere | Subclasses cannot bypass checks |
| Value objects (money, dates, shapes) | Immutability | readonly (PHP 8.2), records, unexported fields (Go) | No history to break |
| One implementation cannot support a method | Split the interface (ISP) | Optional capability interface | No refused bequest |
| Generic collections / repositories in PHP | @template, @template-covariant | PHPStan level 6+ or Psalm | Variance checked statically |
| Public HTTP API or event schema | Additive changes only | Pact, schema registry compatibility checks | Clients you do not control |
| Go standard interfaces | Follow the doc contract | iotest, fstest, race detector | Compiler checks nothing else |
| Callers branching on concrete types | Polymorphism | Visitor or strategy | Removes the type switch |
In architecture: from a single process to a distributed system
LSP scales from a method to a fleet: what changes is who the "callers" are and how many versions of the "subtype" exist at once.
Monolith: one process, one codebase
All callers are visible and compile together, so the type checker and the contract tests see everything. Simplest correct usage: interfaces with documented contracts, final concrete classes, a contract suite per interface with several implementations. Example: a Laravel monolith with a PaymentGateway contract, StripeGateway and FakeGateway; one PaymentGatewayContract PHPUnit suite runs against both (Stripe in test mode, nightly).
Modular monolith and multiple databases
Modules expose interfaces to each other. Each module's public interface is a contract other modules program against, and its implementation can be replaced (a module moved to a different database, say orders from MySQL to PostgreSQL) only if the contract holds. Example: the Billing module exposes InvoiceQuery::forCustomer(int $id): InvoiceList with a documented ordering (newest first). The module team rewrites it on a PostgreSQL read model; the contract test for ordering is what tells them they forgot ORDER BY issued_at DESC.
Microservices: versions as subtypes
Now the substitution is in time: v2 of a service replaces v1 while old clients still run. Rules: additive changes, tolerant readers (ignore unknown fields: the "liberal in what you accept" half of Postel's law), no new required fields, no new error codes without a fallback, and consumer-driven contracts in the provider's pipeline. Example flow:
1 mobile v3.2 ──POST /v1/orders {"qty":2}──▶ orders-api v7 (adds optional "currency")
2 orders-api v7 ──OrderPlaced{v1 fields + currency}──▶ Kafka ──▶ billing (ignores currency), analytics (uses it)
3 Provider CI: verify pacts from mobile 3.2, web 2026.11, billing -> can-i-deploy = yes
4 Later: mobile 3.4 sends currency; only when no consumer lacks it does the API make it requiredDistributed data: replicas, caches and multi-region Good to know
Infrastructure substitution is LSP at the data layer. A read replica is not a substitute for the primary for a caller that relies on read-your-writes; a cache-aside layer is not a substitute for the database for a caller that relies on freshness; a multi-region "active-active" store is not a substitute for a single-primary one for a caller that relies on uniqueness. Each is a subtype with a weaker postcondition (staleness), so either the abstraction must declare that ("may return data up to N seconds old") or callers that need the stronger promise must be routed to the primary. Example: UserRepository::find() documented as "fresh" must not be pointed at a replica; add UserReadModel::find() that documents bounded staleness and route the profile page to it. The engines' guarantees are on Replication & Failover.
Scaling path: 1×, 10×, 100×
| Load / organisation | What LSP work looks like |
|---|---|
| 1×: one team, one app | Documented interfaces, final classes, contract tests for adapters and fakes |
| 10×: several teams, modules or services | Module contracts versioned; Pact between services; additive-only API policy; deprecation headers |
| 100×: many consumers you do not know | Schema registry with compatibility modes (BACKWARD, FORWARD, FULL), API versioning in the URL or media type, long deprecation windows, telemetry on old-version usage before removal |
Lab: refactoring kata
The kata uses the code on this page. Every output below was produced by running it with Go 1.27 (the module declares go 1.24); PHP steps describe the expected observation because the outcome depends on your Laravel app.
Setup.
cd docs/snippets/solid/go
go vet ./lsp/... # cleanStep 1: observe the Rectangle/Square violation, then the fix.
go run ./lsp/kata
# before: Stretch(Rectangle) = 20
# before: Stretch(Square) = 16
# after: TotalArea = 36Observation: same call, same static type, different result. After the refactor there is no Stretch that can be fooled: shapes only promise Area().
Step 2: the caller-side violation of io.Reader.
go run ./lsp/kata # fourth line
# io.Reader: len=11 naive=8 correct=11Observation: NaiveCount loses the three bytes iotest.DataErrReader returns together with io.EOF. Change NaiveCount to add n before checking err and rerun: 11.
Step 3: a Less that is not a strict weak ordering.
# sort with < : [3 NaN 1 2 NaN 0]
# sort.Float64s : [NaN NaN 0 1 2 3]Observation: no panic, no error, unsorted output. Replace the closure with slices.SortFunc(xs, cmp.Compare[float64]) and the result is sorted with NaNs first.
Step 4: catch a lying fake with the contract suite. Uncomment TestLyingStoreContract in lsp/contract/store_test.go:
go test ./lsp/contract/
# --- FAIL: TestLyingStoreContract (0.00s)
# --- FAIL: TestLyingStoreContract/miss_returns_ErrNotFound (0.00s)
# store.go:30: Get(absent) error = <nil>, want ErrNotFound
# FAILObservation: the fake compiles as a Store but is not a subtype. Comment the test back in after fixing LyingStore.Get to return ErrNotFound.
Step 5: verify a reader with iotest.
go test ./lsp/reader/ -run TestUpper -v
# === RUN TestUpperHonoursReaderContract
# --- PASS: TestUpperHonoursReaderContract (0.00s)Now break the postcondition "n is the number of bytes placed in p": in Upper.Read, add if n > 1 { n-- } after the inner Read, and rerun:
go test ./lsp/reader/ -run TestUpper
# --- FAIL: TestUpperHonoursReaderContract (0.00s)
# count_test.go:15: ReadAll(small amounts) = "HELO RADR"
# want "HELLO, READER"Observation: the decorator still compiles as an io.Reader; only the contract test notices that it under-reports bytes.
Step 6 (Laravel): enforce the discount postcondition. In a Laravel 13 app, copy Before.php and write a test Checkout::pay(1000, new LoyaltyPoints(1500)). Expected before: -500. Switch to After.php: expected 0. Then try final class Greedy extends DiscountPolicy { public function apply(int $t): int { return 2000; } }: expected PHP fatal error Cannot override final method App\Pricing\DiscountPolicy::apply() at class load.
Common misconceptions
| Belief | Reality |
|---|---|
| "LSP is about inheritance." | It is about any substitution: interface implementations, fakes, drivers, service versions. Liskov separated subtype from subclass in 1987. |
| "If it compiles, it substitutes." | Compilers check signatures. Pre/postconditions, invariants and history are checked by tests or not at all. |
| "A subtype must behave identically." | It may accept more and promise more. It may not demand more or deliver less. |
| "Adding validation in a subclass is safer." | Rejecting inputs the base accepted strengthens the precondition and breaks valid callers. |
| "Square is a Rectangle, so it should extend it." | Only for immutable shapes. With independent setters, Square breaks Rectangle's postcondition. |
"Throwing NotImplementedException is fine for unsupported methods." | That is Refused Bequest; split the interface or use an optional capability interface. |
"instanceof is a harmless special case." | It means callers know subtypes; every new subtype is a change to callers. |
| "Fakes only need to make the test pass." | A fake that differs from production makes tests predict nothing. Run the contract suite against it. |
| "Go has no inheritance, so LSP does not apply." | It applies to every interface; io.Reader and sort.Interface document contracts the compiler cannot check. |
| "A new API version is a separate thing." | To existing clients it is a substitute; breaking them is an LSP violation across the network. |
| "Being liberal in what you accept is always good." | It creates dependencies on leniency (Hyrum's law); be liberal deliberately and document it. |
| "SQLite in tests proves the PostgreSQL code works." | Different locking, typing and SQL; run the contract suite on the real engine. |
Cheat sheet
| Topic | What to remember |
|---|---|
| Rule | Require no more, promise no less (Weirich, via Cheney) |
| Preconditions | Same or weaker in the subtype |
| Postconditions | Same or stronger in the subtype |
| Invariants | Kept; added ones must not contradict inherited postconditions |
| History constraint | No state changes the supertype forbids (immutable stays immutable) |
| Variance | Parameters contravariant, returns covariant; PHP 7.4+ supports both; Go requires exact match |
| Exceptions | Same set or narrower; translate infra errors at the adapter |
io.Reader | Handle n > 0 before err; 0, nil means nothing happened; never retain p |
sort.Interface | Less must be a strict weak ordering; NaN breaks < |
| Smells | Refused Bequest, NotImplementedException, instanceof, type switch on concrete types |
| Enforcement | Types → final Template Method → contract tests → Pact |
| Fakes | Same contract suite as the real adapter |
| APIs | Additive changes, tolerant readers, expand and contract, consumer-driven contracts |
| Optional capabilities | Separate interface (fs.ReadFileFS, LockProvider), base contract complete without it |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why is class Square extends Rectangle a subclass but not necessarily a subtype? Must-know
Answer
Answer: Subclassing reuses code; subtyping is a behavioural promise. With independent setters, Rectangle promises that setting the width leaves the height unchanged; Square cannot keep that, so a caller written against Rectangle (Stretch) gets 16 instead of 20.
2 — A subtype's method requires a non-empty string where the base accepted any string. Which rule does it break? Important
Answer
Answer: It strengthens the precondition. Callers that legitimately passed an empty string now fail.
3 — Is it an LSP violation for a subtype to return a narrower type, e.g. User instead of ?Model? Important
Answer
Answer: No. Covariant returns promise more; PHP 7.4+, Java and C# 9+ allow it.
4 — What is the history constraint, and how can a subtype break it without breaking any invariant? Good to know
Answer
Answer: It restricts how state may evolve between two moments (e.g. a bag's bound never changes). A subtype can add a new method like setBound that keeps the invariant (size at most bound) but lets the bound change, breaking callers who relied on it being fixed.
5 — Your Go function drops the last bytes of some streams. What part of the io.Reader contract did it ignore? Must-know
Answer
Answer: Read may return n > 0 together with a non-nil error such as io.EOF; the caller must process the n bytes before looking at the error.
6 — Why does sort.Slice with xs[i] < xs[j] produce unsorted output for floats with NaN? Good to know
Answer
Answer: Less must be a strict weak ordering; every comparison with NaN is false, so NaN appears "equal" to everything and transitivity of equivalence breaks.
7 — Your in-memory fake returns null for a missing user; the real API adapter throws on 404. What do you do? Important
Answer
Answer: Decide the contract (null on miss), make the adapter translate 404 to null, and run one contract test suite against both so they cannot drift again.
8 — When is a type check on an interface (not a concrete class) acceptable? Important
Answer
Answer: When it checks an optional capability whose absence is part of the documented contract and the caller has a fallback, e.g. fs.ReadFile checking fs.ReadFileFS or Laravel checking LockProvider.
9 — How do final and the Template Method pattern enforce a postcondition? Good to know
Answer
Answer: The public method is final and owned by the base class, which checks inputs and clamps or asserts the output; subclasses only implement a protected hook and cannot bypass the checks.
10 — Why is adding a strict validation rule to an existing API endpoint an LSP issue? Important
Answer
Answer: The new version is a substitute for the old one; rejecting requests the old version accepted strengthens the precondition and breaks existing clients.
11 — What does a consumer-driven contract test verify that a provider's own tests do not? Important
Answer
Answer: That the provider still satisfies the specific requests and responses each real consumer depends on, before it is deployed.
12 — Name two ways SQLite in tests fails to substitute for PostgreSQL. Important
Answer
Answer: No SELECT ... FOR UPDATE, and type affinity that accepts text in an INTEGER column (plus missing ILIKE/jsonb operators).
Glossary
| Term | Meaning |
|---|---|
| Liskov Substitution Principle (LSP) | Objects of a subtype must be usable wherever the supertype is expected without changing program correctness |
| Subtype | A type whose objects keep every behavioural promise of another type |
| Subclass | A class that reuses another's code through inheritance; not necessarily a subtype |
| Behavioral subtyping | Liskov & Wing's 1994 definition based on specifications, not signatures |
| Liskov & Wing | Authors of A Behavioral Notion of Subtyping (1994) |
| Signature rule | Contravariant arguments, covariant results, no new exceptions |
| Precondition | What must hold before a call; may be weakened in a subtype |
| Postcondition | What a call guarantees; may be strengthened in a subtype |
| Invariant | Property true of an object between calls |
| History constraint | Restriction on how an object's state may change over time (the constraint rule) |
| Covariance | A type that varies in the same direction as the subtype (return types) |
| Contravariance | A type that varies in the opposite direction (parameter types) |
| Design by contract | Meyer's method of specifying software with require, ensure and invariant (Eiffel) |
| Subcontracting | Meyer's term for redefinition under inheritance; "dishonest" if it strengthens pre or weakens post |
| Refused Bequest | Code smell: a subclass that does not want some inherited behaviour |
NotImplementedException / UnsupportedOperationException | Exceptions thrown for unsupported inherited methods; a sign of Refused Bequest |
Type switch / instanceof | Caller-side check of the concrete type; the LSP symptom |
| Template Method | Base method fixes the algorithm and calls overridable hooks |
final | PHP/Java keyword preventing override or extension |
@template / @template-covariant | PHPDoc generics read by PHPStan and Psalm |
| Contract test | One test suite run against every implementation of an abstraction |
| Fake | A working lightweight implementation used in tests; must honour the contract |
| Strict weak ordering | Irreflexive, transitive ordering with transitive equivalence; required of sort.Interface.Less |
iotest / fstest | Go packages that test io.Reader and fs.FS contracts |
| Optional interface | A capability interface checked by type assertion, absent-safe by contract |
LockProvider | Laravel cache contract for stores that support atomic locks |
| Backward compatibility | A new version accepts everything old clients send and returns what they expect |
| Robustness principle / Postel's law | Be conservative in what you send, liberal in what you accept (RFC 761, RFC 1122) |
| Hyrum's law | With enough users, every observable behaviour becomes depended on |
| Consumer-driven contract | Consumers publish expectations; the provider verifies them before deploying |
| Pact | A code-first tool for consumer-driven contract testing of HTTP and message integrations |
| Expand and contract | Additive schema/API change, migrate consumers, then remove; keeps old clients working |
strictFunctionTypes | TypeScript option that checks function parameter contravariance (not methods) |
| mypy | Python type checker that reports incompatible overrides |
References
- Barbara Liskov, "Data Abstraction and Hierarchy", keynote address, OOPSLA '87 Addendum to the Proceedings, October 1987. PDF
- Barbara Liskov and Jeannette M. Wing, "A Behavioral Notion of Subtyping", ACM TOPLAS 16(6), November 1994. PDF
- Eiffel Software, "Design by Contract: Introduction". eiffel.com
- Robert C. Martin, "The Liskov Substitution Principle", The C++ Report, March 1996 (quoted as summarised in his May 1996 DIP column). DIP PDF
- Dave Cheney, "SOLID Go Design", 2016. dave.cheney.net
- Go documentation:
io,sort,io/fs; source of the quoted comments: io.go, sort.go - J. Postel (ed.), RFC 761, DoD Standard Transmission Control Protocol, 1980. rfc-editor.org; R. Braden (ed.), RFC 1122, 1989. rfc-editor.org
- Pact documentation, "Introduction". docs.pact.io; Ian Robinson, "Consumer-Driven Contracts: A Service Evolution Pattern". martinfowler.com
- PHP Manual: Covariance and Contravariance, Final Keyword
- PHPStan, "Generics in PHP using PHPDocs". phpstan.org
- Java Language Specification SE 21, chapter 8 (§8.4.8.3). docs.oracle.com
- Microsoft Learn: C# version history, Covariance and Contravariance (C#)
- TypeScript,
strictFunctionTypes; mypy, Class basics - Refactoring.Guru, "Refused Bequest". refactoring.guru
- Laravel 13 documentation: Mocking, Contracts, Cache (atomic locks); framework source Cache/Repository.php