Preventing subclassing
medium 45 minA subclass can replace your methods, and then your promises are only as good as theirs.
Video lesson · Chapter 1 of 6
Make a prediction
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
1998
Leonid Mikhajlov and Emil Sekerinski study the fragile base class problem at ECOOP and ask which rules for parents and children avoid it.
2011
C++11 adds
finalfor classes and virtual functions.2016
Swift 3 separates
openfrompublic(SE-0117): outside its module a public class cannot be subclassed unless it is open.2016
Python 3.6 adds
__init_subclass__(PEP 487). A parent can now react when a child is defined, and refuse it.2019
Python 3.8 adds
typing.final(PEP 591), a mark for type checkers.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.
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.
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
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)The bad shape: everything can be replaced
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
1/3Private and final
The balance is private, and the method that guards it is final.
usesextends (is a)
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
| Language | Whole class | One method | A list | Checked |
|---|---|---|---|---|
| Java | final class, also records. Private constructors | final | sealed ... permits (17) | Compiler and JVM |
| C++ | class X final (C++11) | Not virtual, or final on an override | std::variant | Compiler |
| C# | sealed class | Not virtual, or sealed override | Private protected constructor | Compiler and runtime |
| Kotlin | The default. open allows | The default. final override | sealed class | Compiler |
| Swift | final, and public without open outside the module | final | enum with values | Compiler |
| Python | @final, or __init_subclass__, or a metaclass | @final, or __init_subclass__ | Union plus assert_never | @final by type checkers only |
| TypeScript | Private constructor, new.target check | A check in the constructor | Union type plus never | Type checker, or your own check at run time |
Which lock?
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
How children get hurt by a parent's change
| The parent changes | The child |
|---|---|
addAll no longer calls add | Counts correctly by accident, until it is changed back |
A new method remove appears | Does not count it |
| A new method with the same name as one in the child | Overrides it without wanting to. C# asks for override, Kotlin too. Java has @Override as an optional mark |
| A field becomes a computed value | A child that set the field has no effect any more |
When
Good reasons to close
| Kind of class | Examples | Why |
|---|---|---|
| Immutable values | String, Integer, LocalDate | A child could have state that changes, or lie in length() |
| Security code | Token check, encryption, login | An override that returns true opens the door |
| Value objects | Money, coordinates, email address | Equality between parent and child cannot be made right in both directions |
| Utility classes | Math, Collections | Only static methods, nothing to inherit |
| Core of a framework | The loop that calls your plugins | Others rely on the order of steps |
| Classes that are not designed for it | Most of them | You 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
RetryPolicyis final and takes aWaitStrategyinterface.- 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
- JEP 409: Sealed Classes
- Java language specification: classes
- java.lang.String
- Oracle: Secure Coding Guidelines for Java SE
- Fragile base class, with the ECOOP 1998 paper
- PEP 591: final
- PEP 487: simpler customisation of class creation
- cppreference: final specifier
- Kotlin: inheritance
- Kotlin: sealed classes
- Swift SE-0117
- .NET CA1852: seal internal types
- Spring: proxying mechanisms
- Mockito 5: inline mock maker by default
- Hibernate user guide: entity classes