Notes
The setup
Here is the setup. A notifier interface has one method, send. Its contract says what it needs and what it gives. It needs text between one and one thousand characters. It gives back a receipt that is never null, and it promises the message is either sent now or queued, never silently lost. Order alerts holds a list of notifiers and sends an order summary of about two hundred characters to each one.
interface Notifier {
// needs: text of 1 to 1000 chars
// gives: a non-null Receipt;
// the message is sent now or
// queued, never silently lost
Receipt send(String text);
}
record Receipt(String channel,
int parts, Status status) { } A broken subtype
Now an SMS channel is added. A single SMS holds one hundred and sixty characters, so the developer makes send throw an exception for anything longer. It compiles, it implements the interface, and its own tests pass with short messages. But order alerts sends two hundred characters, which the contract allows, and the SMS channel blows up. The caller did nothing wrong.
public Receipt send(String text) {
if (text.length() > 160)
throw new IllegalArgumentException(
"SMS max is 160 chars");
return new Receipt("sms", 1, SENT);
} Why it hurts
The usual reaction makes things worse. Someone adds a check in order alerts: if this notifier is the SMS one and the text is long, cut it first. Now the caller knows about a concrete class, the same check gets copied into every other caller, and the next channel with a limit needs another branch. The interface was supposed to hide these differences. A subtype that breaks the contract turns polymorphism back into a pile of if statements.
for (Notifier n : channels) {
if (n instanceof StrictSmsNotifier
&& text.length() > 160) {
n.send(text.substring(0, 160));
} else {
n.send(text);
}
}
every caller now knows about SMS The idea
The principle says: if code works correctly with a type, it must keep working correctly when you pass any subtype instead. Notice that this is not about compiling. The compiler happily accepted the SMS class. It is about behaviour. A subtype must keep every promise the parent makes, so that callers never need to know which subtype they have.
- if code works correctly with
- a type, it must still work
- correctly when you pass any
- of its subtypes instead
- not about what compiles
- about behaviour: a subtype
- must keep every promise
- the parent makes
Contracts
To reason about this, think of every method as a contract with three parts. The precondition is what the caller must make true before calling, like text of one to one thousand characters. The postcondition is what the method guarantees afterwards, like a non null receipt and no lost message. An invariant is something that is always true about the object, like a sent count that never goes down.
- precondition: what must be
- true before the call
- (text is 1 to 1000 chars)
- postcondition: what is true
- after the call
- (non-null receipt, not lost)
- invariant: what is always
- true about the object
- (a sent count never drops)
Rule 1: ask no more
The first rule: a subtype may not demand more than the parent. The parent accepts one to one thousand characters. A subtype that accepts up to five thousand is fine, because every caller that respected the parent still works. A subtype that accepts only one hundred and sixty is broken, because it rejects calls the parent promised to handle. That is exactly the SMS bug.
- parent accepts: 1 to 1000
- subtype accepts 1 to 5000:
- fine, it is more relaxed
- subtype accepts 1 to 160:
- broken, it is stricter
- a subtype may not demand
- more than the parent did
Rule 2: promise no less
The second rule is the mirror: a subtype may not promise less. A push channel returns null when the phone is offline and simply drops the message. The parent promised a non null receipt and no lost messages. So the caller crashes with a null pointer exception, or worse, the customer never hears about the order and nobody knows. Promising more is fine. Promising less breaks callers.
public Receipt send(String text) {
if (!deviceOnline)
return null; // message lost
return new Receipt("push", 1, SENT);
}
caller reads receipt.status():
NullPointerException More rules
A few more rules complete the checklist. Keep every invariant the parent has. Do not throw new kinds of exceptions that callers have no reason to expect. Do not allow state changes the parent never allowed, such as a subtype of an immutable type that can be modified. Keep the same meaning for return values. And never override a method with an empty body just to make it do nothing.
- keep the parent's invariants
- no new kinds of exception
- the caller cannot expect
- no state changes the parent
- never allowed (a read-only
- type that becomes writable)
- same meaning for return values
- do not ignore the call with
- an empty override
Fix 1: keep the promise
The first fix is to make the subtype keep the promise. The splitting SMS notifier accepts any text the contract allows and cuts it into parts of one hundred and sixty characters. A two hundred character summary becomes two parts. The receipt reports how many parts were sent, which is extra information, and that is allowed. The caller needs no special check.
public Receipt send(String text) {
int parts = (text.length() + 159)
/ 160;
for (int i = 0; i < parts; i++)
gateway.sendPart(slice(text, i));
return new Receipt("sms", parts, SENT);
}
200 chars: 2 parts, no exception Fix 2: never lose it
The push channel is fixed the same way. When the phone is offline, it stores the message in a pending queue and returns a receipt with the status queued. When the phone comes back online, it sends everything in the queue. The parent contract said sent now or queued, never lost, and this class keeps exactly that promise.
public Receipt send(String text) {
if (!deviceOnline) {
pending.add(text);
return new Receipt("push", 1,
QUEUED);
}
return new Receipt("push", 1, SENT);
}
void deviceCameOnline() { flush } Run-through
Run the same order alerts loop again with no special cases. Email sends the summary in one part. SMS splits it and sends two parts. Push sees the phone is offline and returns queued. Every channel returns a real receipt, nothing throws, nothing is lost, and order alerts never asks which class it is talking to. That is substitutability.
Fix 3: change the shape
Sometimes a subtype truly cannot keep the promise. Then change the design, not the caller. Either make the parent contract honest, for example a max length method that every caller must respect, or stop inheriting and use a separate interface or composition. In real life an SMS is a kind of notification, but in code, is a only counts if the behaviour matches.
- option A: make the parent
- contract honest, e.g. add
- maxLength() that every
- caller must respect
- option B: do not inherit;
- use a separate interface
- or composition
- "is a" in real life is not
- enough; behaviour decides
How to spot it
How do you spot a violation? Instance of checks in callers are the loudest signal. So are overrides that throw unsupported operation exception, overrides with empty bodies, and comments that say do not call this method on that subtype. A great test is to run the parent's test suite against every subtype. If a subtype fails a test written for the parent, it breaks the contract.
- instanceof checks in callers
- overrides that throw
- UnsupportedOperationException
- empty overrides that do
- nothing
- docs that say "do not call
- this on subtype X"
- tests for the parent that
- fail for a subtype
Where you see it
Java itself has a famous case. Timestamp extends date, but its own documentation says not to treat a timestamp as a date, because its equals method is not symmetric with the date version. The list interface takes another approach: add is documented as an optional operation, so an unmodifiable list may throw. That keeps the rule, technically, by weakening the parent contract, and it still surprises people.
- java.sql.Timestamp extends
- java.util.Date, yet its docs
- say not to treat it as a
- Date; equals is not
- symmetric with Date
- List.add is an "optional
- operation": unmodifiable
- lists throw on add, so
- the contract warns you
Related ideas
This principle holds the others together. The open closed principle only works if new classes behave like the interface promises. Composition over inheritance often avoids the problem, because there is no subtype to break the contract. Interface segregation helps too, since a small contract is easier to keep. And design by contract is the formal version of these precondition and postcondition rules.
- open/closed: new classes plug
- in safely only if they keep
- the contract
- composition over inheritance:
- no subtype, no broken promise
- interface segregation: small
- contracts are easier to keep
- design by contract: the formal
- version of these rules
In LLD interviews
In LLD interviews, check each subclass against what its parent promises. Can every payment method handle every valid amount, or does one throw for small payments? Does an express elevator that skips floors still honour the elevator contract when someone requests floor three? The common mistake is inheriting only to reuse code. If the child cannot keep the parent's promises, use composition instead.
- parking lot: every Vehicle
- must fit the spot it asks for
- payments: every method must
- return a result, not throw
- for valid amounts
- elevator: an express car that
- skips floors breaks Elevator
- mistake: inheritance just to
- reuse code