Records and Sealed Classes
Design a small subsystem that relies on Records and Sealed Classes. Outline components, data flow, failure modes, and metrics.
Answers use simple, clear English.
Quick interview answer
Use Records and Sealed Classes as the core idea. Example shape: API result type: sealed interface Result permits Success, Failure with record payloads..
Detailed answer
Use Records and Sealed Classes as the core idea. Example shape: API result type: sealed interface Result permits Success, Failure with record payloads.. Watch for: Records shallowly immutable — mutable fields inside break contract.. Measure success via latency/error/saturation. 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: Mid-level.
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?