25-Comp-B11 Advanced Software Design · May 2014
Nivaar worked solution (AI-drafted; not reviewed by a licensed engineer)
Question text not reproduced: the examination questions are © Engineers and Geoscientists BC. Open the official past paper (linked at the top of this page) to read the question, then follow the worked solution below.
The Liskov Substitution Principle (LSP, Barbara Liskov, 1987) states that objects of a subtype must be substitutable for objects of its supertype without altering the correctness of a program: anywhere client code holds a reference typed as the supertype, substituting a subtype instance must not break any guarantee that client code relies on.
Formalized in Design-by-Contract terms (Question 10), a subtype's precondition must be no STRONGER than the supertype's (the subtype cannot demand more of callers than the supertype promised to require), and its postcondition must be no WEAKER (the subtype must still deliver at least what the supertype's contract promised) — informally, "contravariant preconditions, covariant postconditions," with invariants preserved as well.
Why it is useful. LSP is the formal underpinning of safe inheritance-based polymorphism: without it, substituting a subtype for its declared supertype silently breaks client code that was written once, correctly, against the supertype's documented contract — defeating the entire purpose of subtype polymorphism (Question 7), which is that client code need not even know which concrete subtype it holds. LSP gives a concrete, checkable test for "is this a valid is-a relationship for INHERITANCE purposes," beyond an informal, real-world "is-a" intuition that can be misleading.
Classic violation. A class Square that extends Rectangle, overriding setWidth/setHeight so both sides stay equal, breaks client code such as r.setWidth(5); r.setHeight(4); assert r.getArea() == 20; — the assertion, valid for any genuine Rectangle, fails for a Square because setting the height silently also changed the width. A square "is-a" rectangle in the everyday geometric sense, but Square is NOT a valid Rectangle SUBTYPE under LSP, because it weakens (drops) the implicit postcondition that setWidth leaves height unchanged.
The practical consequence guides Question 23's inheritance-vs-delegation choice directly: when a natural is-a relationship cannot preserve the supertype's contract, prefer composition/delegation over inheritance.