AlgoViz

Preventing subclassing

medium 45 min

A subclass can replace your methods, and then your promises are only as good as theirs.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:44

See it run

Which method runs, who can replace it, and where a child is refused.

Operations

The broken promise

RentService trusts Account. A child removes the check.

Step 1 of 5

The promise

rentRentServicebalance okyesaccountAccountnotesnoneAccount partparentcents10000

An Account never goes below zero. RentService relies on it.

Step 1: The promise

class FreeWithdrawAccount(BankAccount):    def withdraw(self, cents):        self.cents -= cents       # no check        return Truedef pay_rent(account):    account.withdraw(90_000)    assert account.cents >= 0
Shows
Why to lock at all
Remember
One child is enough

The caller cannot see which child it got. That is the point of a type.

In the real world

The same preventing subclassing doing real jobs. Pick one and step through it.

Who may extend, and what may be replaced.

Step 1 of 5

Final method

childrenoverridesexample
Final methodyesnot that oneAccount

Children are welcome. One step is locked.

Step 1: Final method

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • A rule that children may replace

    critical

    The invariant is only as good as the worst child.

    Wrong
    def withdraw(self, cents):    ...            # anybody may override
    Right
    @finaldef withdraw(self, cents):    ...    self._on_withdraw(cents)
  • Believing @final

    major

    Python does not check it when the program runs.

    Wrong
    @finalclass Token: ...
    Right
    @finalclass Token:    def __init_subclass__(cls, **kw):        raise TypeError("Token is final")
  • Extending to count

    major

    The parent may call its own methods, and the child counts twice.

    Wrong
    class CountingList(list):    ...
    Right
    class CountingList:    def __init__(self, inner):        self._inner = inner
  • A default in a closed switch

    major

    It hides the next kind that is added.

    Wrong
    case _:    return "pending"
    Right
    case _:    assert_never(result)
  • Final for everything

    minor

    Entities and proxied services need children made by the framework.

    Wrong
    # Javafinal class OrderEntity { ... }
    Right
    # Javaclass OrderEntity { ... }   // the ORM subclasses it

Interview tips

  • Start with the promise

    • Name it
    • Who relies on it?
    • Who could break it?
  • Smallest lock

    • Method
    • List
    • Class
  • Leave a way

    • Hook after the change
    • Interface and wrapper
    • Listener
  • Know the limits

    • Not immutability
    • Not speed
    • Not a wall against attackers