Skip to content

Checkpoint: Valid Values

The Course
•
20 min study

Close the earlier solutions before starting. Today combined method contracts, constructor validation, value equality and fixed choices. The checkpoint asks you to choose which tool protects which rule. A correct output alone is not enough: invalid values must be rejected before state changes.

Work through the example

The example measures the contract of a small limit object. A rejection check must prove that an exception was actually thrown. Putting a failure after construction prevents a false pass when validation disappears. Catch the expected exception type, not every possible error; AssertionError deliberately escapes.

Before Run, write the output and identify the exact line responsible for each result. Each editor is a separate program; names and edits in one box do not carry into the next.

Predict, then run Java
public class Main {
    public static void main(String[] args) {
        try {
            new Limit(0);
            throw new AssertionError("zero accepted");
        } catch (IllegalArgumentException expected) {
            System.out.println("Zero rejected");
        }
        System.out.println(new Limit(1).value());
    }
}

final class Limit {
    private final int value;

    Limit(int value) {
        if (value < 1) {
            throw new IllegalArgumentException("positive limit required");
        }
        this.value = value;
    }

    int value() {
        return value;
    }
}
Check your prediction
Text
Zero rejected
1

Compare the behavior

Normalization and validation are separate decisions. This ID allows surrounding spaces, but rejects an empty result. Because we return normalized text, callers need not repeat trimming. We are not promising general-purpose identifier validation; the task's contract controls what is accepted.

Trace the changed case Java
public class Main {
    public static void main(String[] args) {
        System.out.println(normalize("  A1  "));
        try {
            normalize("   ");
        } catch (IllegalArgumentException expected) {
            System.out.println("Blank rejected");
        }
    }

    static String normalize(String id) {
        if (id == null || id.trim().isEmpty()) {
            throw new IllegalArgumentException("id required");
        }
        return id.trim();
    }
}
Check your prediction
Text
A1
Blank rejected

Plan your acceptance cases

Before writing the complete implementation, predict these cases without running the solution. Keep the requirements above as the authority; this table highlights distinct promises rather than prescribing a particular class layout.

CaseExpected behaviorSkill it checks
Padded valid IDStore its trimmed spellingNormalization before storage
Blank ID or null StateReject constructionInvariant
Two unrelated OPEN ticketsSame state does not imply same identityEquality policy

After your first version works, choose one row and introduce a plausible defect that it should expose. Restore the correct version, then recreate the central operation without the worked example. If one skill is missing, revisit that lesson before combining more features.

Practice independently

Exercise

Checkpoint: Valid Values: practice

Build an immutable Ticket with a normalized nonblank ID and a nonnull State (OPEN or CLOSED). Expose id() and state(). Test that " A1 " becomes "A1", the state is retained, blank IDs are rejected, and null states are rejected. Print Ticket checks passed. Do not add equality based only on state: unrelated tickets can both be open.

Spend a few minutes on your own first. Compile after one small change, read the first error, and check the result against the requirements rather than matching the solution's layout.

Your workspace Java
public class Main {
    public static void main(String[] args) {
        // Define Ticket and State, then write your checks.
        System.out.println("Checkpoint workspace");
    }
}
Hint 1: the idea

Define validity before deciding fields and accessors. Tests must prove both accepted and rejected cases.

Hint 2: a first step

Write the enum first. In the constructor reject null/blank values before storing the trimmed ID.

Show one solution

One possible implementation follows. Compare its decisions with yours: which values can change, what inputs are accepted, and what would expose a mistake?

Java
public class Main {
    public static void main(String[] args) {
        Ticket ticket = new Ticket(" A1 ", State.OPEN);
        check(ticket.id().equals("A1"));
        check(ticket.state() == State.OPEN);

        try {
            new Ticket(" ", State.OPEN);
            throw new AssertionError("blank id accepted");
        } catch (IllegalArgumentException expected) {
            // Expected rejection.
        }
        try {
            new Ticket("A1", null);
            throw new AssertionError("null state accepted");
        } catch (IllegalArgumentException expected) {
            // Expected rejection.
        }
        System.out.println("Ticket checks passed");
    }

    static void check(boolean condition) {
        if (!condition) {
            throw new AssertionError("ticket contract");
        }
    }
}

enum State {
    OPEN,
    CLOSED
}

final class Ticket {
    private final String id;
    private final State state;

    Ticket(String id, State state) {
        if (id == null || id.trim().isEmpty() || state == null) {
            throw new IllegalArgumentException("valid id and state required");
        }
        this.id = id.trim();
        this.state = state;
    }

    String id() {
        return id;
    }

    State state() {
        return state;
    }
}

Expected output:

Text
Ticket checks passed

Change it and test again

Mutate the constructor to accept blanks, then to store the untrimmed ID. Your checks should fail for both defects. Restore the implementation. Add a distinct ticket with the same state and explain why that state does not identify the ticket.

Explain before moving on

Can you solve this without reading the solution? If not, redo just the missing skill: constructor rules, enum use, or rejection tests. Tomorrow you will store many values and decide whether duplicates are allowed.

Was this article helpful?

Your response is saved on this device.