A compact constructor is a record constructor that removes the repeated parameter list and field assignments, leaving the body focused on what makes the data valid. The record header supplies the components, and the runtime handles the routine assignment. That makes the form especially useful when a record needs semantic guardrails without traditional constructor ceremony. section 2.6.1
Reject invalid data
A Rational record can enforce its basic invariant at construction time: reject a zero denominator with an IllegalArgumentException. The constructor protects the value’s meaning before invalid data enters the program. section 2.6.1
Normalize incoming values
Validation is only one use. A Rational compact constructor can calculate a greatest common divisor and divide both components by it, transforming equivalent inputs into a simplified representation before assignment. section 2.6.1
Use compact constructors to:
- Enforce what a data type means, rather than accumulate unrelated business rules. section 2.6.1
- Transform incoming arguments when the representation must be simplified or protected from unexpected mutability. section 2.6.1
