Builder: a setter validates its own range eagerly

Checking a value inside the setter itself rejects bad input the moment it is supplied, rather than waiting until build() to report a problem that could be far from where it was introduced. Eager validation gives a more precise error at the exact call that caused it.

Code
class Percentage {
    static class Builder {
        private int value;
        Builder value(int v) {
            if (v < 0 || v > 100) throw new IllegalArgumentException("out of range: " + v);
            value = v;
            return this;
        }
        int build() { return value; }
    }
}
String outcome;
try {
    new Percentage.Builder().value(150);
    outcome = "accepted";
} catch (IllegalArgumentException e) {
    outcome = "rejected eagerly: " + e.getMessage();
}
System.out.println(outcome);
Output
rejected eagerly: out of range: 150
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms