Sub topic 8
Validating Data with Compact Constructors
In the last chapter you wrote a record in one line. Java gave you a constructor, accessors, equals, hashCode, and toString for free. But that free constructor accepts any values at all. A Range could start at 10 and end at 2, and a Fraction could have zero on the bottom. This chapter shows how to stop bad data at the door, using a compact constructor.
Why Validation Belongs in the Constructor
A constructor is the special code that runs when you create an object with new. A record object can't be changed after it's built, so the constructor is your one chance to check its data.
If the constructor rejects bad values, every Range in your program is known to be valid. Code that uses a Range never has to check again. This idea is called a class invariant: a rule that is always true for every object of a type.
Here is the problem without any checks:
record Range(int start, int end) {}
public class Main {
public static void main(String[] args) {
Range broken = new Range(10, 2);
System.out.println(broken); // Range[start=10, end=2]
}
}Java happily builds this broken range. Let's fix that.
The Canonical Constructor
The canonical constructor is the constructor whose parameters match the record's components exactly, in the same order and with the same types. For record Range(int start, int end), the canonical constructor takes (int start, int end).
If you don't write one, Java generates it. The generated version does just two things:
// What Java generates for you (you don't write this)
Range(int start, int end) {
this.start = start;
this.end = end;
}You can write this constructor yourself if you want to add checks. That is called an explicit canonical constructor:
record Range(int start, int end) {
Range(int start, int end) {
if (start > end) {
throw new IllegalArgumentException("start must not exceed end");
}
this.start = start;
this.end = end;
}
}This works, but you have to repeat the parameter list and write every assignment by hand. If you forget one assignment, the code won't compile. For a record with six components, that's a lot of repetition.
The Compact Constructor
A compact constructor is a shorter way to write the canonical constructor. You write the record's name, then a body, with no parentheses and no parameter list:
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 ok = new Range(1, 5);
System.out.println(ok);
try {
new Range(5, 1);
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
}Output:
Range[start=1, end=5]
Rejected: start must not exceed endNotice what is missing. There's no (int start, int end) and there's no this.start = start. Java fills in both:
- The parameters
startandendare declared for you, with the same names and types as the components. - Your body runs first.
- After your body finishes, Java assigns each parameter to its field.
If your body throws an exception, step 3 never happens. No object is created.
Common Validation Checks
Most checks fall into a few groups. Here's a record that uses several of them:
import java.util.Objects;
record Product(String name, int quantity, double price) {
Product {
Objects.requireNonNull(name, "name must not be null");
if (name.isBlank()) {
throw new IllegalArgumentException("name must not be blank");
}
if (quantity < 0) {
throw new IllegalArgumentException("quantity must be 0 or more, got " + quantity);
}
if (price <= 0) {
throw new IllegalArgumentException("price must be positive, got " + price);
}
}
}
public class Main {
public static void main(String[] args) {
System.out.println(new Product("Pen", 3, 1.50));
try {
new Product("Pen", -1, 1.50);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
try {
new Product(null, 1, 1.50);
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
}
}Output:
Product[name=Pen, quantity=3, price=1.5]
quantity must be 0 or more, got -1
name must not be nullObjects.requireNonNull is a helper from java.util.Objects. It throws a NullPointerException with your message if the value is null, and does nothing otherwise.
| Check | Typical code | Exception to throw |
|---|---|---|
| Value must not be null | `Objects.requireNonNull(x, "x")` | `NullPointerException` |
| Number in a range | `if (n < 0) throw ...` | `IllegalArgumentException` |
| Text not empty | `if (s.isBlank()) throw ...` | `IllegalArgumentException` |
| Two components agree | `if (start > end) throw ...` | `IllegalArgumentException` |
Normalizing Values
Sometimes the input is fine but should be cleaned up first. Turning input into one standard form is called normalizing. In a compact constructor you do this by reassigning the parameter. Java then stores the new value in the field.
import java.util.Objects;
record Username(String value) {
Username {
Objects.requireNonNull(value, "value must not be null");
value = value.strip().toLowerCase();
if (value.isEmpty()) {
throw new IllegalArgumentException("username must not be empty");
}
}
}
public class Main {
public static void main(String[] args) {
Username a = new Username(" Alice ");
Username b = new Username("ALICE");
System.out.println(a); // Username[value=alice]
System.out.println(a.equals(b)); // true
}
}Both usernames end up stored as alice, so they're equal. Normalizing helps equals work the way people expect.
Here's a math example. The fractions 1/-2 and -1/2 are the same number. If we always keep the minus sign on top, they become equal records:
record Fraction(int numerator, int denominator) {
Fraction {
if (denominator == 0) {
throw new IllegalArgumentException("denominator must not be zero");
}
if (denominator < 0) {
numerator = -numerator;
denominator = -denominator;
}
}
}
public class Main {
public static void main(String[] args) {
Fraction f = new Fraction(1, -2);
System.out.println(f); // Fraction[numerator=-1, denominator=2]
System.out.println(f.equals(new Fraction(-1, 2))); // true
}
}The One Thing You Cannot Do
Inside a compact constructor, you can't assign to the fields directly. This does not compile:
record Range(int start, int end) {
Range {
this.start = 0; // compile error: cannot assign a value to final variable start
}
}Java assigns the fields itself at the end, and each field can only be assigned once. Change the parameter instead (start = 0;), and Java copies it into the field for you.
Adding Other Constructors
You can add more constructors with different parameters. Each one must start by calling another constructor with this(...). In the end, every path goes through the canonical constructor, so your checks always run:
record Range(int start, int end) {
Range {
if (start > end) {
throw new IllegalArgumentException("start must not exceed end");
}
}
// A range holding a single number
Range(int value) {
this(value, value);
}
}
public class Main {
public static void main(String[] args) {
System.out.println(new Range(7)); // Range[start=7, end=7]
}
}Nobody can skip your validation. The chapter on methods and static factories shows another way to offer handy creation options.
A Quick Look Ahead: Mutable Components
If a component is a mutable object, such as a List, the compact constructor is also where you make a safe copy:
import java.util.List;
record Team(String name, List<String> members) {
Team {
members = List.copyOf(members);
}
}This uses the same reassignment trick you saw above. The chapter on shallow immutability explains why this copy matters.
Summary
- The canonical constructor's parameters match the record's components. Java generates it if you don't write one.
- A compact constructor is written
RecordName { ... }. Its parameters are declared for you, and the fields are assigned after your body runs. - Throw
IllegalArgumentExceptionorNullPointerExceptionto reject bad data. When you throw, no object is created. - Reassign a parameter to normalize it. Never assign
this.fieldin a compact constructor. - Extra constructors must call
this(...), so validation always runs.
Exercise
Write a record Percentage(int value) whose compact constructor rejects any value below 0 or above 100 with an IllegalArgumentException. What happens when you run new Percentage(150)?
Show answer
record Percentage(int value) { Percentage { if (value < 0 || value > 100) { throw new IllegalArgumentException("value must be 0 to 100, got " + value); } } } — Calling new Percentage(150) throws IllegalArgumentException with the message "value must be 0 to 100, got 150", and no Percentage object is created.
Exercise
Write a record Email(String address) that rejects null, removes spaces at the start and end, converts the address to lower case, and rejects it if it does not contain "@". Should the trimming happen before or after the "@" check, and why?
Show answer
record Email(String address) { Email { java.util.Objects.requireNonNull(address, "address must not be null"); address = address.strip().toLowerCase(); if (!address.contains("@")) { throw new IllegalArgumentException("not an email: " + address); } } } — Normalize first, then validate, so the check runs on the exact value that will be stored.
Exercise
A classmate writes record Box(int width) { Box { this.width = Math.abs(width); } } and gets a compile error. Explain the error and fix it.
Show answer
In a compact constructor, Java assigns the fields itself after the body runs, so assigning this.width directly is not allowed (the field is final and may be assigned only once). The fix is to reassign the parameter: record Box(int width) { Box { width = Math.abs(width); } }