A customer returns a kurta to an online clothing store. The courier picks it up, and the store's code calls refund on the order's payment. For a UPI (Unified Payments Interface) payment or a card payment, the money goes back to where it came from. Then the store starts taking cash on delivery, and the same call has nowhere to send the money.
The Liskov Substitution Principle says that code written for a type must keep working when it is handed any subtype of that type.
The principle
A subtype is a class that implements an interface or extends another class. The caller holds the base type, here a PaymentMethod, and does not know which class is behind it. The principle says that the caller should never need to know.
The compiler checks only part of this. It checks that every subtype has the right methods, with the right parameter and return types. It cannot check what a method does. So the principle is about behaviour, not signatures. Each base type makes a promise to its callers, and a subtype keeps that promise in three ways:
- It accepts at least what the base accepts. The rules a caller must meet before a call are its preconditions, and a subtype may not make them stricter. If the base refunds any amount up to what was paid, a subtype that refunds only the full amount breaks a caller that refunds one missing item.
- It promises at least what the base promises. What is true after the call is its postcondition, and a subtype may not deliver less. If the base says the money is on its way when
refundreturns, a subtype may not return without sending it. - It keeps what is always true, and throws no new surprises. Invariants are facts that hold for the object's whole life, like a wallet balance that never goes below zero, and a subtype must keep them. A subtype also must not throw an exception that the base never warned callers about.
The principle does not ask subtypes to behave the same. They can differ in anything the promise leaves open. A card refund can take days, and a wallet credit is instant. If the base never promised a speed, both keep the promise.
Example: refunds in an online store
The store takes UPI and cards. Every payment method can refund itself:
/** How a customer paid for an order. */interface PaymentMethod { /** * Sends the amount back to where the money came from and returns the * refund reference. When it returns, the money is on its way. */ String refund(long amount);}UpiPayment and CardPayment each keep the transaction ID and ask the bank to reverse that transaction. ReturnDesk runs when a returned item reaches the warehouse. It was written against the interface, and it is correct for both payment methods:
final class ReturnDesk { private final Notifier notifier; ReturnDesk(Notifier notifier) { this.notifier = notifier; } void completeReturn(Order order, long amount) { String reference = order.payment().refund(amount); order.markRefunded(reference); notifier.tell(order.customerPhone(), "Your refund has started. Reference " + reference); }}A second caller, MissingItemDesk, refunds the price of one item that was missing from a delivered order.
The change request
The store starts taking cash on delivery (COD). A COD customer pays the courier in cash, so there is no account to send a refund back to. The developer still has to write refund, because the interface asks for it:
final class CashOnDelivery implements PaymentMethod { @Override public String refund(long amount) { throw new UnsupportedOperationException("Cash cannot be sent back to where it came from"); }}This compiles, and every signature matches. It still breaks the promise. When a COD customer returns the kurta, the courier brings it back, and completeReturn throws on its first line. The order is never marked refunded, and the customer gets nothing back.
A refund that does nothing and returns a made-up reference is worse. The order is marked refunded and the customer gets the message, but no money moves. Nobody finds out until the customer complains.
The type check
The quick fix is a type check in the caller:
String reference;if (order.payment() instanceof CashOnDelivery) { reference = order.customerWallet().credit(amount);} else { reference = order.payment().refund(amount);}COD refunds now go to the customer's store wallet, and the bug is gone from ReturnDesk. The check is a sign that the subtype broke its promise. The caller no longer trusts PaymentMethod, so it asks which class it has. MissingItemDesk needs the same check. A caller written next year must know to add it too, or COD refunds throw again. Each new payment method with its own refund rule means finding every check again. The Open/Closed Principle page shows the same cost for a switch.
Reshaping the promise
CashOnDelivery cannot keep the promise "refund to where the money came from". So we stop asking every payment for that. Every payment can answer a smaller question: where should a refund of this payment go? Sending the money becomes its own interface:
/** Where refunded money goes. */interface RefundRoute { /** Starts the refund and returns its reference. When it returns, the money is on its way. */ String sendRefund(long amount); /** Where the money lands, for the message to the customer. */ String description();} /** How a customer paid for an order. */interface PaymentMethod { /** Where a refund of this payment goes. Never null. */ RefundRoute refundRoute();}UpiPayment and CardPayment implement both interfaces and return themselves as the route. StoreWallet is a route that adds the amount to the customer's balance. CashOnDelivery answers with the customer's wallet:
final class CashOnDelivery implements PaymentMethod { private final StoreWallet customerWallet; CashOnDelivery(StoreWallet customerWallet) { this.customerWallet = customerWallet; } @Override public RefundRoute refundRoute() { return customerWallet; // cash has no account to go back to }}completeReturn has one path again, and it tells the customer where the money went:
void completeReturn(Order order, long amount) { RefundRoute route = order.payment().refundRoute(); String reference = route.sendRefund(amount); order.markRefunded(reference); notifier.tell(order.customerPhone(), "Your refund is on its way to " + route.description() + ". Reference " + reference);}Every PaymentMethod can now keep its promise, because each one can name a route. Every RefundRoute keeps its promise too, because each one sends the money. The COD decision lives in one class, CashOnDelivery, and no caller makes it. Suppose the store later lets COD customers ask for a bank transfer. That is a new RefundRoute and a change inside CashOnDelivery, and ReturnDesk does not change.
How should the promise change for cash on delivery?
Say that refund may throw
The interface documents that refund can throw UnsupportedOperationException. The contract is now honest. But every caller must catch the exception and decide where the money goes, and a caller that forgets still compiles.
Promise less: the customer gets the money back
refund now promises only that the customer gets the money back, and CashOnDelivery.refund credits the StoreWallet. This keeps the principle with no new interface. But callers cannot learn where a refund will go without sending it.
Ask every payment for its refund routeOur pick
PaymentMethod asks a question that every payment can answer, and the answer is an object that can always send the money. A return form can call description() on the route and show where the money will go before any money moves. StoreWallet is a route that any payment can hand back. The cost is one more interface.
A known case: Java's List.of
List.of(...) returns a list that cannot be changed, and its add throws UnsupportedOperationException. This looks like the COD mistake. But the List interface documents add as an "optional operation", which an implementation may refuse with exactly this exception. So the list keeps the written contract, and the cost moves to the callers:
static void addFreeGift(List<String> items) { items.add("free tote bag");} addFreeGift(new ArrayList<>(List.of("kurta"))); // worksaddFreeGift(List.of("kurta")); // throws UnsupportedOperationExceptionBoth calls compile. Whether addFreeGift works depends on where the list came from, and the type List does not say. A contract that lets any subtype refuse is easy to keep, but it gives callers little to rely on. A separate type for lists that can be changed would let the compiler catch this call. Splitting List into a read-only type and a type that can be changed is the Interface Segregation Principle: each caller depends only on what it uses.
When not to
The principle protects callers that hold the base type. A class that extends another only to reuse its code has no such caller yet, though the compiler would accept one. That class is usually clearer if it holds the other class as a field instead of extending it. Also, do not split an interface for every difference between subtypes. A difference the promise never mentions, like how fast the money arrives, breaks nothing. Reshape the abstraction only when a subtype cannot do what callers rely on.
In an interview
When you draw an interface, say in one line what each method promises. If the interviewer adds a kind that cannot keep that promise, change the interface instead of adding a type check, and say why. The Composite pattern page makes this choice for add: it lives on folders only, so a file never has a method that can only throw.
Common mistakes:
- Judging by signatures. A subtype that compiles can still break every caller.
- Throwing from a method the base promised. Callers written for the base type have no reason to catch an
UnsupportedOperationException. - A method that quietly does nothing. It avoids the exception and breaks the promise where nobody can see it.
- A type check in the caller.
instanceof CashOnDeliverymeans the abstraction is wrong, and every new caller must repeat the check.
Summary
- Code written for a base type must keep working with any subtype of it.
- The principle is about behaviour: a subtype accepts at least what the base accepts, promises at least what the base promises, keeps the base's invariants, and throws no new surprises.
- A subtype that throws, or quietly does nothing, where the base made a promise breaks the callers written for the base.
- An
instanceofcheck in a caller is a sign of this. The fix is to reshape the abstraction so that every subtype can keep the promise, here by asking each payment for its refund route. - A contract may let a subtype refuse, as
Listdoes foradd, but then every caller must be ready for the refusal.