CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 2 of 6 · 2 min read

Validate inputs

Check arguments at the start of a method.

Think of a security desk at a building. A guard who checks passes at the entrance finds a bad pass at once. A bad pass found on the tenth floor is harder to trace.

EJ Item 49 says to check parameters at the start of a method and to catch a fault as near to its cause as possible. Without the check, EJ lists three outcomes: a confusing failure in the middle of the work, a silent wrong answer, or, worst, an object left in a damaged state that fails later somewhere unrelated.

record Booking(String room, int hours) {
    Booking {
        Objects.requireNonNull(room, "room");
        if (hours < 1 || hours > 8)
            throw new IllegalArgumentException("hours must be 1 to 8: " + hours);
    }
}

new Booking(null, 2) fails at once with a null pointer error naming room. new Booking("A1", 12) fails with "hours must be 1 to 8: 12". The bad object never exists, so nothing downstream needs to check it again. EJ suggests Objects.requireNonNull, which also returns its argument, so it can sit inside an assignment.

Three standard exceptions cover most checks: NullPointerException for a null that is not allowed, IllegalArgumentException for a bad value, and IllegalStateException for a call made at the wrong time. EJ Item 72 advises using the standard ones, since every Java programmer knows them.

Document the rules too, in the Javadoc @throws tag, so callers know what the method promises. Private helpers may use assert or skip checks, because the class controls every call to them.

Precondition

A precondition is a rule about the inputs or state that must hold before a method runs. The caller must meet it, and the method checks it.

Example: hours must be between 1 and 8.

Check yourself: 1. What does new Booking("A1", 12) print as its message? 2. Which exception fits a call on a booking that has already been cancelled? 3. Why check at the start and not in the middle?