IT Essentials

Java Sealed Types: The Price of Compile-Time Safety

How the compile-time safety of Java sealed types and exhaustive switches turns into a breaking change for downstream code the moment a new permitted subtype is added.

What sealed types change

In Java, classes and interfaces are open for extension by default, so the compiler cannot know in advance which subtypes a type may have. Sealed classes and interfaces put a boundary there: once the permitted subtypes are declared, everything else is rejected, and the compiler knows the complete set of cases the type can take.

How exhaustive switch works

With a closed set of cases, the compiler can check whether a switch handles every subtype. Handle them all and you can write the switch without a default branch; miss one and you get a compile error. When a new case appears, the compiler points at every spot that needs updating — the core appeal of sealed types.

The trap: adding a subtype becomes a breaking change

The GeekNews piece frames this as the flip side of the safety net: as its title says, “a new subtype can break existing code.” When a library adds a subtype to the permitted list, every downstream exhaustive switch that knows nothing about it stops compiling. The very strength of having the compiler catch missing cases means that an ordinary form of API evolution turns into a breaking change for consumers. Adding a default branch keeps the code compiling, but it gives up the exhaustiveness check, and handling of the new type can quietly disappear into the default. Either way, the cost is paid somewhere.

Beyond Java

The tradeoff is not Java-specific. When a type system buys compile-time safety by closing a hierarchy, extending that hierarchy is itself what breaks downstream code. Library designers should treat “will more subtypes be added to this hierarchy?” as part of their compatibility contract; consumers should treat exhaustive switches as a deliberate choice between safety and extensibility. How to communicate new subtypes, and how much reliance on default branches is acceptable, remain decisions each team has to make.

Sources

Drafted by AI from the original sources and reviewed by an editor before publishing. Check the sources for the authoritative details.

#Java #sealed types #exhaustive switch #type safety #API evolution

← IT essentials