Video in progress
What signs in code tell you the Liskov principle has been violated?
The main sign is that code written against the parent type behaves differently when it gets a child type: instanceof checks, UnsupportedOperationException in an override, strengthened conditions or weakened guarantees.
📖 Answer
LSP: if you put an object of the child type in place of any object of the parent type, the program should keep working correctly.
What to look for in code:
- An empty override or one that throws an exception:
class ReadOnlyAccount extends Account {
@Override
void withdraw(BigDecimal amount) {
throw new UnsupportedOperationException();
}
}
Every piece of code that accepts an Account is now at risk.
-
instanceofin the caller:if (acc instanceof ReadOnlyAccount) return;means the abstraction is lying. -
A strengthened precondition: the parent accepts
amount > 0, while the child requiresamount > 1000. -
A weakened postcondition: the parent says "I return a sorted list", but the child doesn't sort.
-
The parent's tests fail for the child. The best check: run the contract tests written for the parent class against every implementation.
The fix is usually to rethink the hierarchy: split ReadOnlyAccount and WithdrawableAccount into separate interfaces. The JDK itself has this flaw: the list returned by List.of(...) throws an exception on add, which is why the documentation calls it an "optional operation".
Sign up to mark studied questions and save your progress.