Skip to the page

OOP and SOLID · mid

Liskov substitution principle

Code written for a parent type must work with every subclass. A subclass that throws when the parent promises to work, such as a FixedDeposit that refuses withdraw, breaks this rule, and the fix is in the hierarchy.

The notes

What you must know

  • Code written for BankAccount expects withdraw to work when funds are enough. A subclass that strengthens the precondition and throws cannot stand in for its parent.
  • Fix the hierarchy, not the caller. Use an Account base (balance, deposit, statement) and a separate Withdrawable capability, or make SavingsAccount and FixedDepositAccount siblings. The nightly job works only on Withdrawable.
  • Or use composition: an account holds a WithdrawalPolicy (allowed, or allowed after maturity with a penalty).
  • instanceof checks in the caller are a smell that the hierarchy is wrong.
  • A real example: Collections.unmodifiableList returns a List whose add throws UnsupportedOperationException. It is a known trade-off in the JDK.
  • Contract tests: write one test suite for the parent contract and run it against every subclass.
  • A protected mutable balance lets subclasses break the invariants of the parent.

The red pen

Common traps: mistake → fix

  • Mistake: LSP is the same as method overriding

    Fix: overriding is allowed; LSP is about keeping the promises of the parent.

  • Mistake: It compiles, so it is fine

    Fix: a compiler does not check behaviour contracts.

  • Mistake: Add an instanceof check in the job

    Fix: that hides the broken hierarchy and spreads the problem.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is the Liskov substitution principle?
  2. A FixedDepositAccount extends BankAccount and throws on withdraw. What is wrong?
  3. How would you restructure it?
  4. How can tests help you find LSP breaks?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview