Sub topic 8
Validating Data with Compact Constructors
A record gives you a constructor for free, but that constructor accepts any values. Nothing stops someone from writing new Range(10, 2), where the start comes after the end. This chapter shows you how to reject bad data, and how to clean it up, before the record is created.
The Canonical Constructor
A canonical constructor is the constructor that takes one parameter for each record component, in the same order. For record Range(int start, int end), the compiler writes one for you that looks like this:
record Range(int start, int end) {
Range(int start, int end) {
this.start = start;
this.end = end;
}
}You can write this constructor yourself and add checks to it. However, you would have to repeat every parameter and every assignment, and that is the kind of boilerplate records were made to remove.
The Compact Form
A compact canonical constructor is a shorter way to write the canonical constructor. It has no parameter list and no parentheses, just the record name and a body. Inside the body you can use the parameters by name. When the body finishes, Java assigns them to the fields for you.
Validation means checking that the data makes sense and refusing it if it does not. Here is a Range that validates its components:
record Range(int start, int end) {
Range {
if (start > end) {
throw new IllegalArgumentException("start must not exceed end");
}
}
}
public class Main {
public static void main(String[] args) {
Range good = new Range(2, 10);
System.out.println(good); // Range[start=2, end=10]
try {
Range bad = new Range(10, 2);
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
}Save this as Main.java and run it with java Main.java. The second call throws an exception, so no broken Range ever exists.
Normalizing Data
Normalizing means changing a value into a standard form, such as trimming extra spaces. In a compact constructor you can reassign a parameter, and the new value is the one that gets stored.
record Username(String value) {
Username {
if (value == null || value.isBlank()) {
throw new IllegalArgumentException("username must not be blank");
}
value = value.trim().toLowerCase();
}
}
public class Main {
public static void main(String[] args) {
Username u = new Username(" Alice ");
System.out.println(u.value()); // alice
}
}The record now holds "alice". Two usernames typed differently but meaning the same thing will be equal.
Compact vs. Full Canonical Constructor
| Feature | Compact constructor | Full canonical constructor |
|---|---|---|
| Parameter list | None | Must list every component |
| Field assignment | Automatic, after the body | You write each `this.x = x` |
| Best for | Checks and small clean-ups | Rare cases that need full control |
Exercises
Exercise
Write a record Percentage(int value) whose compact constructor throws an IllegalArgumentException when value is less than 0 or greater than 100.
Show answer
record Percentage(int value) { Percentage { if (value < 0 || value > 100) { throw new IllegalArgumentException("value must be between 0 and 100"); } } }
Exercise
In a compact constructor for record Email(String address), you write address = address.toLowerCase();. What does new Email("[email protected]").address() return, and why?
Show answer
It returns "[email protected]". Reassigning the parameter inside the compact constructor changes the value that Java stores in the field once the body finishes.