AlgoViz

Liskov substitution (LSP)

medium 55 min

An 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

0:00 / 5:06

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

toolResizeToolexpects50gotrRectanglewidth0height0

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

childin the bathexpectsa squeakgetsbath duckRubberDucksqueeze()squeakfloat()yes

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

    critical

    The supertype says that everyone can. Callers have no plan for the exception.

    Wrong
    class Archive(Store):    def save(self, key, text):        raise PermissionError
    Right
    class Archive(Reader):   # no save at all    def load(self, key): ...
  • Asking for the class

    major

    The check repairs one caller. The next one fails, and the next subclass is not in the list.

    Wrong
    if not isinstance(b, Penguin):    b.fly()
    Right
    for f in flyers:   # list[Flyer]    f.fly()
  • A silent override

    critical

    Doing nothing looks like success. Data is lost without an error.

    Wrong
    class NullStore(Store):    def save(self, key, text): pass
    Right
    class Discard:   # says what it does    def drop(self, key, text): pass
  • A private limit

    major

    Calls that are legal for the supertype fail here only.

    Wrong
    class ShortStore(Store):    def save(self, k, t):        if len(t) > 100: raise ValueError
    Right
    # split into pieces of 100 inside, join in load,# and keep the limit of 1000 of Store
  • Leaking foreign errors

    major

    The caller handles StoreDown. An OSError goes past it.

    Wrong
    def load(self, key):    return open(key).read()
    Right
    try: 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