Records and Sealed Classes
What are the key trade-offs of Records and Sealed Classes? When would you choose it vs alternatives?
Answers use simple, clear English.
Quick interview answer
Pros: Less boilerplate; algebraic modeling with compiler-checked exhaustiveness. Cons: Records shallowly immutable — mutable fields inside break contract.
Detailed answer
Pros: Less boilerplate; algebraic modeling with compiler-checked exhaustiveness. Cons: Records shallowly immutable — mutable fields inside break contract. Decision: pick when benefits outweigh operational cost. Core: record Point(int x, int y) generates constructor, equals, hashCode, toString. sealed permits restricts subclasses — exhaustive pattern switch in Java 21+. Real-time example: API result type: sealed interface Result permits Success, Failure with record payloads. Pros: Less boilerplate; algebraic modeling with compiler-checked exhaustiveness. Cons: Records shallowly immutable — mutable fields inside break contract. Common mistakes: Adding mutable collections without defensive copy in compact constructor. Best practices: Use compact constructor to validate; combine sealed + records for domain ADTs. Audience level: Architect.
Full explanation
record Point(int x, int y) generates constructor, equals, hashCode, toString. sealed permits restricts subclasses — exhaustive pattern switch in Java 21+.
Real example & use case
API result type: sealed interface Result permits Success, Failure with record payloads.
Pros & cons
Pros: Less boilerplate; algebraic modeling with compiler-checked exhaustiveness. Cons: Records shallowly immutable — mutable fields inside break contract.
Common mistakes
Adding mutable collections without defensive copy in compact constructor.
Best practices
Use compact constructor to validate; combine sealed + records for domain ADTs.
Follow-up questions
- How would you test Records and Sealed Classes?
- What metrics prove Records and Sealed Classes is healthy in prod?
- How does Records and Sealed Classes change at 10× traffic?