A constructor is a useful boundary for turning loose requirements into valid data. Put checks on the data type itself so newly created instances cannot violate constraints, even when callers ignore documentation. section 3.2.2 section 9.6
Validating a measurement
A Measurement constructor can reject malformed sample identifiers, negative elapsed days, and contact angles outside the permitted range. This prevents incorrect measurements from entering the rest of the program. section 3.2.2
Listing 3.13 Defending invariants during construction
record Measurement(
String sampleId,
int daysElapsed,
double contactAngleDegrees) {
Measurement { #A
if (!sampleId.matches("(HEAT|AIR|UV)-\\d+")) { #B
throw new IllegalArgumentException(
"Must honor the form {CuringMethod}-{number}" +
"Where CuringMethod is one of (HEAT, AIR, UV), " +
"and number is any positive integer"
);
}
if (daysElapsed < 0) { #C
throw new IllegalArgumentException(
"Days elapsed cannot be less than 0!");
}
if (!(value >= -180.0 && value < 180.0)) { #C
throw new IllegalArgumentException(
"Contact angle must be between -180 and +180");
}
}
}Inspect the compact constructor to see how each invariant becomes executable code at the creation boundary. section 3.2.2
Construction-time validation improves safety but does not preserve meaning by itself. After construction, a value such as contactAngleDegrees can still behave as an ordinary double, requiring stronger data types when semantic distinctions must survive transformations. section 3.2.2

















