الانتقال إلى المحتوى
Software ArchitectureSOLID· 7 دقائق للقراءة

Liskov Substitution Is About Behavior, Not Inheritance That Compiles

The compiler checks signatures. Substitutability depends on what callers can rely on: accepted inputs, promised results and the exceptions they must handle.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
محتويات المقال

Support reports that refunding one item from a three-item order fails, but only when the order was paid with a voucher. VoucherGateway inherits from PaymentGateway, overrides RefundAsync, compiles, and passes its own tests. It also throws for any amount other than the full captured amount. RefundService was written against PaymentGateway, whose contract allows partial refunds, so it never expected that. The first fix proposed in review is if (gateway is VoucherGateway).

The common misconception

The belief: if a class inherits from a base class, or implements an interface, and the code compiles, then it can be used anywhere the base type is expected. The Liskov Substitution Principle is satisfied by construction.

It's a reasonable belief because the compiler does check a lot: method names, parameter and return types, overrides, accessibility. Liskov and Wing agree that's required: "Clearly subtypes must provide the expected methods with compatible signatures." Many tutorials also teach LSP as a rule about class hierarchies, and Robert C. Martin admits: "People (including me) have made the mistake that this is about inheritance."

The half-truth: compatible signatures are necessary. As the paper puts it, though, type checking "captures only a small part of what it means for a program to be correct".

What actually happens

Substitutability is about what callers can tell

Liskov and Wing's 1994 paper frames the question this way: objects of a subtype "ought to behave the same as those of the supertype as far as anyone or any program using supertype objects can tell." Their Subtype Requirement says that any property provable about objects of the supertype must also hold for objects of the subtype. Martin's 2020 phrasing of the is shorter: "A program that uses an interface must not be confused by an implementation of that interface."

Signatures can't tell a stack from a queue

The paper's own example: a stack and a queue can both have a put that adds an element and a get that removes one. By the signature rules, either could be a legal subtype of the other. But "a program written in the expectation that x is a stack is unlikely to work correctly if x actually denotes a queue, and vice versa." Same shape, different behavior, and the compiler can't see the difference.

The behavioral rules

The paper turns "behaves the same" into checkable rules for each method the subtype provides:

  • : the subtype's method must work in every state the supertype's method accepts. It may accept more, never less. VoucherGateway breaks this by refusing partial amounts.
  • : the subtype may guarantee more than the supertype, never less.
  • Exceptions: a subtype's method may not signal exceptions the supertype's doesn't, "since a caller of a method on a supertype object should not expect to handle an unknown exception."
  • Invariants and history: what's always true of the supertype stays true. The paper shows that a set you can delete from is not a subtype of a set that only grows, even with matching signatures.

It's not about inheritance at all

The paper notes that a subtype providing a supertype's methods doesn't mean it inherits their code, "simply that it provides methods with the same behavior". Martin makes the same point from the other side: LSP is about subtyping, all implementations of interfaces are subtypes of the interface, and duck types are subtypes of an implied interface. His warning about the cost: if an implementation confuses the user of the base type, "if/switch statements will proliferate."

The fix: promise only what every implementation keeps

C#
public class PaymentGateway{    // Contract: refunds any amount up to what was captured    public virtual Task RefundAsync(Payment p, decimal amount) =>        Task.CompletedTask; // stand-in for the provider's refund call}public sealed class VoucherGateway : PaymentGateway{    // Compiles, but demands more than the base type promised    public override Task RefundAsync(Payment p, decimal amount) =>        amount == p.Captured            ? base.RefundAsync(p, amount)            : throw new InvalidOperationException("Full refunds only");}// Refunding one item of three now fails only for voucher orders,// and RefundService starts growing: if (gateway is VoucherGateway)

The behavioral difference is now part of the types. Card gateways implement IPartialRefunds; the voucher gateway implements only IRefunds, and its contract never promised partial refunds. RefundService takes IPartialRefunds for item returns and needs no type checks. The bug moved from production to the compiler, which is the best place to catch a broken promise.

MythReality
If it compiles, it's substitutableThe compiler checks signatures; LSP is about the behavior callers rely on
LSP is about inheritanceMartin: it's about subtyping, including interface implementations and duck types
A subtype may be stricter about its inputsIt may accept more, never less; and it may promise more, never less
Throwing a new exception in an override is fineCallers of the base type don't expect it; Liskov and Wing rule out new exceptions
Sharing code is a good reason to subclassSubtyping requires the same behavior; reusing code isn't the test

How to apply it in your project

  1. Write the contract downIn the base type's doc comments, state which inputs are valid, what each method guarantees, and which exceptions callers must handle.
  2. Search for the smellsLook for overrides that throw NotSupportedException or do nothing, and for callers that check concrete types with is, as or type switches.
  3. Share contract testsRun the same test suite against every implementation of an interface or base class, including fakes used in other tests.
  4. Split promises that not everyone keepsWhen an implementation can't honor part of a contract, give that part its own interface, or use composition instead of inheritance.

Key takeaways

  • LSP is about behavior: code that uses a type must not be surprised by any of its subtypes.
  • Compatible signatures are necessary but not enough; a stack and a queue can share them.
  • A subtype may accept more and promise more, never demand more, deliver less or throw new exceptions.
  • It applies to interfaces and duck types, not only to class inheritance.
  • Type checks against subtypes and overrides that refuse to work are signs the contract is wrong; split it.

📚 المصادر

  1. A Behavioral Notion of Subtyping — Barbara H. Liskov and Jeannette M. Wing, ACM TOPLAS (1994)
  2. Solid Relevance — Robert C. Martin, The Clean Code Blog (2020)
  3. ICollection<T>.Add(T) Method — .NET API reference, Microsoft Learn
  4. ICollection<T>.IsReadOnly Property — .NET API reference, Microsoft Learn

التعليقات (0)