Record deconstruction extracts a record’s components directly inside a pattern, keeping branching logic focused on the data it needs. section 4.2.2
From object binding to component extraction
A conventional pattern binds the whole profile: `case PhysicalProfile p when p.age().value() >= 18 -> calculateBmiCategoryForAdult(p);`. Deconstruction binds the needed components instead: `case PhysicalProfile(Gender gender, Age age, WeightInPounds w, HeightInInches h) when age.value() >= 18 -> calculateBmiCategoryForAdult(w, h);`. The second form makes the adult branch’s inputs visible at the point where the branch is selected. section 4.2.2
Use deconstruction when a pattern branch needs particular record components rather than the complete object. Combined with a guard, it places type testing, extraction, and eligibility checking in one readable case. section 4.2.2
Listing 4.3 Defining a clear and type-safe physical profile
public record Age(int value) {
public Age {
if (value < 0 || value > 150) {
throw new IllegalArgumentException("Age must " +
"be between 0 and 150.");
}
}
}
public record HeightInInches(double value) {
public HeightInInches {
if (value <= 0) {
throw new IllegalArgumentException("Height must be greater " +
"than 0 inches.");
}
}
}
public record WeightInPounds(double value) {
public WeightInPounds {
if (value <= 0) {
throw new IllegalArgumentException("Weight must be greater " +
"than 0 pounds.");
}
}
}
public record PhysicalProfile(Gender gender,
Age age,
WeightInPounds weight,
HeightInInches height) {
}
The supporting record definitions show the strongly typed components available for deconstruction: gender, age, weight, and height. section 4.2.2
