CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 2 of 6 · 2 min read

The problem

Same call, different result.

Think of a door with a lock. Pushing it does nothing when locked, opens it when unlocked, and closes it when open and held. The same push gives three different results, depending on the state of the door.

A meeting room booking has the same life. It is requested, then confirmed, then checked in. It can be cancelled before check in. The rules are these: a request may be confirmed or cancelled; a confirmed booking may be checked in or cancelled; a checked-in booking cannot be cancelled; a cancelled booking cannot do anything more.

A first version keeps the status in a field and checks it in every method.

enum Status { REQUESTED, CONFIRMED, CHECKED_IN, CANCELLED }

class Booking {
    private Status status = Status.REQUESTED;

    void confirm() {
        if (status == Status.REQUESTED) status = Status.CONFIRMED;
        else throw new IllegalStateException("cannot confirm when " + status);
    }
    void checkIn() {
        if (status == Status.CONFIRMED) status = Status.CHECKED_IN;
        else throw new IllegalStateException("cannot check in when " + status);
    }
    void cancel() {
        if (status == Status.REQUESTED || status == Status.CONFIRMED) status = Status.CANCELLED;
        else throw new IllegalStateException("cannot cancel when " + status);
    }
}

This is fine for four states and three actions. It grows poorly. GoF names the problem: state held as data values leads to look-alike conditional statements scattered through the operations, and adding a state may mean changing several of them. Another weakness is that transitions are not written down anywhere. They appear only as assignments to a variable, spread over many methods. HF meets the same trouble in a gumball machine whose states multiply as new features arrive.

State machine

A state machine is a design where an object is always in one of a fixed set of states, and each event moves it to another state or is refused.

Example: a booking that moves from requested to confirmed to checked in.

Check yourself: 1. What are the four states and which moves are legal? 2. Why do the if checks scatter? 3. Where are the transitions written in the first version?