Liskov substitution (LSP)
medium 55 minAn object of a subtype must be usable wherever the supertype is expected, with no surprise for the caller.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Put another object in the same place, make the same calls, and watch what the caller sees.
Operations
Square as Rectangle
The same three calls on two objects. The caller never learns which one it has.
Step 1 of 8
A real rectangle
The tool will set two sides and expects 50.
Step 1: A real rectangle
def resize(r: Rectangle): r.set_width(5) r.set_height(10) return r.area()class Square(Rectangle): def set_width(self, w): self.w = self.h = w def set_height(self, h): self.w = self.h = h- Use it to
- Show a wrong result
- Watch out for
- No crash, no warning
- 5 x 10 expected
- got 100
Say the numbers: 50 expected, 100 got. Then say that `resize` is correct.
In the real world
The same liskov substitution doing real jobs. Pick one and step through it.
Looks, floats and is squeezed. What does the child get?
Step 1 of 4
The saying
If it looks, swims and quacks like a duck, it probably is one. For callers: what counts is what it does.
Step 1: The saying
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Taking a promise back
criticalThe supertype says that everyone can. Callers have no plan for the exception.
Wrongclass Archive(Store): def save(self, key, text): raise PermissionErrorRightclass Archive(Reader): # no save at all def load(self, key): ...Asking for the class
majorThe check repairs one caller. The next one fails, and the next subclass is not in the list.
Wrongif not isinstance(b, Penguin): b.fly()Rightfor f in flyers: # list[Flyer] f.fly()A silent override
criticalDoing nothing looks like success. Data is lost without an error.
Wrongclass NullStore(Store): def save(self, key, text): passRightclass Discard: # says what it does def drop(self, key, text): passA private limit
majorCalls that are legal for the supertype fail here only.
Wrongclass ShortStore(Store): def save(self, k, t): if len(t) > 100: raise ValueErrorRight# split into pieces of 100 inside, join in load,# and keep the limit of 1000 of StoreLeaking foreign errors
majorThe caller handles StoreDown. An OSError goes past it.
Wrongdef load(self, key): return open(key).read()Righttry: return open(key).read()except FileNotFoundError: raise NotFound(key)except OSError as e: raise StoreDown(str(e)) from e
Interview tips
Write the promises
- Accepts, gives, errors
- Always, and over time
- One sentence each
Question each arrow
- Is it true always?
- Would a caller be surprised?
- If not sure, compose
Prove it for all
- One suite, a maker
- Edge values and limits
- Run it on wrappers too
Repair upwards
- Smaller type above
- Move callers
- Then move the class