Java / Java 21 Coding Standards Interview Questions
How can you optimize code readability using record patterns and deconstruction?
A record pattern lets a switch or instanceof check destructure a record's components directly in the pattern itself, binding each component to a named variable in one step instead of matching the record and then calling its accessors separately.
flowchart LR
A["case Point(int x, int y) when x == y ->"] --> B[Bind x and y directly from the record's components]
B --> C[Use x and y immediately in the branch body]
record Point(int x, int y) {} record Line(Point start, Point end) {} static String describe(Object obj) { return switch (obj) { case Line(Point(var x1, var y1), Point(var x2, var y2)) when x1 == x2 -> "vertical line"; case Line l -> "line"; default -> "unknown"; }; }
The readability win compounds with nesting: a nested record pattern like the Line example above expresses "a line whose two points share an x-coordinate" in a single case label, where the pre-Java-21 equivalent would need several lines of accessor calls just to get at x1 and x2.
Coding standards recommend record patterns whenever a method already receives a record and immediately needs its inner components rather than the record itself, since skipping the intermediate accessor calls removes a layer of indirection between the pattern and the logic that uses it.
More Related questions...