liveBook · Manning

Record deconstruction

As explained in The Art of Code

Record deconstruction is a pattern-matching feature that extracts a record's components directly within a pattern.

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

How The Art of Code covers it

How deep it goes
Demonstrates syntax and rationale through BMI dispatch, stopping short of broader pattern-matching internals.
Examples
Uses a PhysicalProfile BMI calculation with adult and child branches and extracted gender, age, weight, and height components.
What it assumes
Assumes familiarity with Java records, switch patterns, binding variables, and guarded cases.
What you can do after
Apply record deconstruction to write guarded branches that expose only the components each operation needs.
How it connects
Connects record deconstruction with pattern matching, guards, records, and control flow.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Art of Code. The section links point to the parts of the book it draws on.