Video in progress
How do you add validation to a record's constructor, and what limitations do records have?
In a "compact" constructor you can validate and normalize the parameters, and the record assigns the fields itself. The limitations: the fields are immutable, it can't extend another class, and you can't add extra instance fields.
📖 Answer
public record Email(String value) {
public Email { // compact constructor
Objects.requireNonNull(value, "email");
value = value.strip().toLowerCase(); // normalization
if (!value.contains("@")) {
throw new IllegalArgumentException("Noto'g'ri email: " + value);
}
}
}
public record Range(int from, int to) {
public Range {
if (from > to) throw new IllegalArgumentException("from > to");
}
public static Range of(int single) { return new Range(single, single); }
public int length() { return to - from; }
}
What you can add to a record: static fields and methods, instance methods, extra constructors (they must call the main one), interface implementations, nested types.
What you can't: an extra instance field, extends, changing a field.
In practice:
- for value objects (
Email,Money,Phone), use a record with a compact constructor: the validation lives in one place, and an invalid object is never created at all; - if you override an accessor, don't change its meaning:
equalsstill works on the fields anyway; - protect list fields with
List.copyOf.
Sign up to mark studied questions and save your progress.