0%
Sealed classes: deliberately closing a hierarchy

Sealed classes

Declaring the complete list of implementations, and what the compiler does with it.

10-15 min

Sealed classes: deliberately closing a hierarchy

In Java 8, a hierarchy has only two possible states: open or closed. You declare a MoyenPaiement interface, and anyone, in any module, can implement it — including with invariants you never anticipated. Or you put final on a class, and nobody can derive anything from it anymore. There is nothing in between. Yet most business models want exactly the middle ground: a payment is a card, a transfer, or a check, that list is complete, and it must not be extended by a third party.

The cost of this gap is paid at every switch. You write a cascade of instanceof checks, finish with else { throw new IllegalStateException("type inconnu"); }, and you know that branch is dead — until the day a colleague adds a fourth implementation. The compiler says nothing, because it doesn't know how many implementations there are. You discover the omission in production, in the form of an exception. A sealed class moves that discovery to compile time: it gives the compiler the exhaustive list of subtypes, and it becomes able to tell you which case you forgot.

Comments

Comments are powered by GitHub Discussions

Sign in with GitHub to join the discussion

Link copied!