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

Preventing subclassing

1:02Reel

Theory

Read or listen first. About 2 min.

What it is

To prevent subclassing is to say that nobody may write a class that inherits from yours. Java and C++ say final class, C# says sealed class, Kotlin and Swift modules are closed unless you say open.

There are softer forms. A final method allows children but not a replacement of that method. A sealed hierarchy (Java, Kotlin, Scala) allows children, but only those on a list. A private constructor stops children because they cannot build the parent's part.

None of this is about changing objects. final class does not make an object immutable, and an immutable object can come from an open class. Often you want both.

Why it exists

Other code believes what your class promises. withdraw never lets the balance go below zero. A child that overrides withdraw can break that while still passing as an account. No reader of your code can see it.

The other direction hurts as well. A child that relies on how the parent works inside breaks when the parent is improved. This is the fragile base class problem. A class that nobody extends can be changed freely.

And a closed list of children is useful information: a switch over the list can be checked for completeness by the compiler.

A short history

  1. 1998

    Leonid Mikhajlov and Emil Sekerinski study the fragile base class problem at ECOOP and ask which rules for parents and children avoid it.

  2. 2011

    C++11 adds final for classes and virtual functions.

  3. 2016

    Swift 3 separates open from public (SE-0117): outside its module a public class cannot be subclassed unless it is open.

  4. 2016

    Python 3.6 adds __init_subclass__ (PEP 487). A parent can now react when a child is defined, and refuse it.

  5. 2019

    Python 3.8 adds typing.final (PEP 591), a mark for type checkers.

  6. 2021

    Java 17 makes sealed classes and interfaces final (JEP 409), after two previews.

Words to know

final class
Cannot be extended.
final method
Cannot be overridden.
sealed (C#)
The same as final in Java, for a class or for one override.
sealed (Java, Kotlin, Scala)
Can be extended, but only by the permitted classes.
non-sealed
Java: a permitted child that opens the family again below itself.
open
Kotlin, Swift: the author allows children.
Invariant
A rule that is always true, such as balance >= 0.
Fragile base class
A parent that cannot be changed safely because children depend on its inner workings.
Self-use
A method of a class that calls another overridable method of the same class.
Hook
A method that exists to be overridden, at a safe place.
Effectively final
No keyword, but no accessible constructor, so no child is possible.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

How it works

Step through the idea, or press Play.

Step 1 of 4

Name the promise. What do others rely on?

Understand it

Start here

Carts that must stop

On Noor's hill, people ride small carts. The rule is simple: every cart stops at the sign. Then people begin to build their own carts from Noor's.

The brake on the hill
STOPCART

Frames 4 to 7 are the four tools of this page. Frame 8 is why you do not use the first one everywhere.

The smell

A child that breaks its parent

Python
class BankAccount:    def __init__(self, cents):        self.cents = cents    def withdraw(self, cents):        if 0 < cents <= self.cents:            self.cents -= cents            return True        return Falseclass FreeWithdrawAccount(BankAccount):    def withdraw(self, cents):          # skips the check        self.cents -= cents        return Truedef pay_rent(account: BankAccount):    account.withdraw(90_000)    assert account.cents >= 0, "the promise of BankAccount is broken"pay_rent(BankAccount(100_000))try:    pay_rent(FreeWithdrawAccount(10_000))except AssertionError as e:    print(e)
An account that never goes below zero, and a child that does. The report trusts the parent's promise.
Edit and run it in your browser

The bad shape: everything can be replaced

RentService+ pay(account)BankAccount# cents: long+ withdraw(c): bool+ cents(): long

1/3A promise

RentService relies on BankAccount: after a withdrawal the balance is not negative.

usesextends (is a)

The good shape: one locked method, one hook

RentService+ pay(account)Account- cents: long+ final withdraw(c): bool+ final cents(): long# onWithdraw(c)

1/3Private and final

The balance is private, and the method that guards it is final.

usesextends (is a)

This is Template method: the recipe is fixed, one step is open.

Tools

Five locks, from weak to strong

  • Final method

    Children may exist. This one step cannot be replaced.

  • Sealed family

    Children may exist, but only those on the list.

  • Final class

    No children at all.

  • Private constructor

    Nobody outside can build the parent's part. Creation goes through a factory.

  • No class to extend

    Callers see an interface and a function that returns one.

By language

LanguageWhole classOne methodA listChecked
Javafinal class, also records. Private constructorsfinalsealed ... permits (17)Compiler and JVM
C++class X final (C++11)Not virtual, or final on an overridestd::variantCompiler
C#sealed classNot virtual, or sealed overridePrivate protected constructorCompiler and runtime
KotlinThe default. open allowsThe default. final overridesealed classCompiler
Swiftfinal, and public without open outside the modulefinalenum with valuesCompiler
Python@final, or __init_subclass__, or a metaclass@final, or __init_subclass__Union plus assert_never@final by type checkers only
TypeScriptPrivate constructor, new.target checkA check in the constructorUnion type plus neverType checker, or your own check at run time

Which lock?

Opening later breaks nobody. Closing later breaks every child that exists. So when in doubt, start closed.

The other danger

The fragile base class

Preventing subclassing protects more than your callers. It also protects you from children that depend on your inner workings. Look at a basket whose add_all calls add.

Counted twice

Neither class is wrong alone. The parent's self-use is an inner detail, and the child depends on it without knowing.

How children get hurt by a parent's change

The parent changesThe child
addAll no longer calls addCounts correctly by accident, until it is changed back
A new method remove appearsDoes not count it
A new method with the same name as one in the childOverrides it without wanting to. C# asks for override, Kotlin too. Java has @Override as an optional mark
A field becomes a computed valueA child that set the field has no effect any more

When

Good reasons to close

Kind of classExamplesWhy
Immutable valuesString, Integer, LocalDateA child could have state that changes, or lie in length()
Security codeToken check, encryption, loginAn override that returns true opens the door
Value objectsMoney, coordinates, email addressEquality between parent and child cannot be made right in both directions
Utility classesMath, CollectionsOnly static methods, nothing to inherit
Core of a frameworkThe loop that calls your pluginsOthers rely on the order of steps
Classes that are not designed for itMost of themYou do not want to promise your inner workings

What you get

  • Invariants: state cannot be broken by an override
  • Security: no hostile replacement
  • Predictability: what you read is what runs
  • Freedom: you may change the inside
  • Sometimes speed: a call to a known method can be inlined

What you pay

  • No fake by subclassing in tests
  • No proxies that work by subclassing
  • Users cannot add a small thing
  • Copies of the class instead of children
  • A new kind needs your release

You publish a library with a class RetryPolicy. Final or open?

BreaksOpen, with protected fields
How
Everything can be overridden, just in case.
Limit
Every protected name is API from now on. You cannot rename a field without breaking somebody.
Choose when
Never in a published library.
WorksFinal, take it or leave it
How
Settings in the constructor, nothing else.
Limit
A user who needs a special wait copies your class.
Choose when
A value with settings only.
StrongFinal class, open seam
How
RetryPolicy is final and takes a WaitStrategy interface.
Limit
One more type. You must choose the seam well.
Choose when
Most library classes.

Summary

The whole topic in one minute.

Close a class when other code relies on an invariant or on a value that does not change. Lock a method when children are welcome but one step must not be replaced. Seal a family when the kinds are known and a switch should be complete.

Design for inheritance or prohibit it. An open class with no thought behind it is the dangerous middle.

Closing costs: no test doubles by subclassing, no framework proxies, no extension by users. Give them an interface and composition instead.

  • Private protects data. final protects behaviour. Immutable protects values over time. They are three different things.
  • Lock the smallest thing: method, list, class.
  • Design for inheritance and document it, or prohibit it.
  • A sealed family turns a forgotten case into a compile error.
  • Give extenders an interface and composition.
  • Opening later is easy, closing later is a breaking change.

Sources