RC RANDOM CHAOS

Sealed Classes' Compile-Time Safety Crumbles Across Module Boundaries

· via Hacker News

Original source

Java sealed classes and exhaustive pattern matching

Hacker News →

Java 17 introduced sealed classes to constrain inheritance to an explicit set of permitted subtypes. This enables the compiler to verify exhaustiveness in switch statements—if all possible types are handled, no default clause is needed. The feature provides genuine compile-time safety guarantees within a single compilation unit.

However, sealed classes introduce a hidden breaking change when exposed in public APIs. Adding new subtypes to a sealed class becomes a version bump that goes undetected until runtime. If a library adds a new subtype and clients don’t recompile against the updated version, old code compiled against the original sealed type will throw a MatchException when encountering the new case—despite having been syntactically valid before. The compiler’s exhaustiveness checking only catches these gaps during initial compilation; it can’t protect against incompatibilities introduced later.

The exhaustiveness guarantees hold only when everything is recompiled together. This severely limits sealed classes’ utility in cross-module scenarios like library APIs. The author argues sealed classes work well for internal component implementation, where recompilation is coordinated. But exposing them publicly invites subtle runtime failures. The Java cryptography API’s recent move to make sealed interfaces part of its public PEM encoding support exemplifies this mistake—future encoding formats could silently break existing applications.

Read the full article

Continue reading at Hacker News →

This is an AI-generated summary. Read the original for the full story.