Records and Sealed Classes
What common mistakes do candidates make around Records and Sealed Classes, and how do you avoid them?
Answers use simple, clear English.
Quick interview answer
Common mistakes: Adding mutable collections without defensive copy in compact constructor. Best practices: Use compact constructor to validate; combine sealed + records for domain ADTs.
Detailed answer
Common mistakes: Adding mutable collections without defensive copy in compact constructor. Best practices: Use compact constructor to validate; combine sealed + records for domain ADTs. 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: Engineering Manager.
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?