State

Intent
Let an object change its behaviour when its situation changes, by putting each situation in its own object instead of spreading conditions across every method.
Application
A box membership can be on trial, active, frozen or expired, and "come in" or "freeze" mean different things in each case. Let each state decide what to do and which one comes next.
MembershipControllerSwitchingMembershipAthlete

The athlete asks MembershipController to come in, which asks SwitchingMembership, highlighted in red, with a switch on the state.

The diagram doesn't change: SwitchingMembership stays highlighted in red, with a default case repeated in every method.

The four states appear, highlighted, as a diagram: renew() goes from TRIAL to ACTIVE, freeze() from ACTIVE to FROZEN, resume() back to ACTIVE, expire() to EXPIRED and renew() from EXPIRED to ACTIVE.

Membership appears, highlighted, handing the action to its current state, ACTIVE, with state.freeze(this).

TRIAL and EXPIRED are highlighted: they only override what they allow, and the default behaviour refuses the rest.

freeze() takes Ana from ACTIVE to FROZEN and resume() brings her back to ACTIVE; both states are highlighted.

POST /api/memberships/1/freeze travels from the athlete to the controller and apply() to the service, which asks the repository for find() and Membership, highlighted, for freeze(); ACTIVE moves to FROZEN, also highlighted.

Inside the Spring context, MembershipRepository, highlighted, stores "FROZEN" in the membership table, also highlighted, only if the row hasn't changed since it was read.

Final view: the athlete, the controller, the service, Membership with its four states, the repository and the table, all inside the Spring context.

Step 1 of 9

The door asks the membership

When the card is tapped, the box's door asks the athlete's membership whether they can come in. The answer depends on its situation:

  • trial: they can come in, up to 3 visits;
  • active: they can come in, freeze or expire;
  • frozen: they can't come in until it's resumed;
  • expired: they can't come in until it's renewed.

The first version, SwitchingMembership, keeps the state in a String and every method runs a switch on it.

Step 2 of 9

One more state, every switch

Look at the default lines: every method repeats "unknown status", because a String accepts anything and a typo like "activ" only shows up at runtime.

And if the box adds a new state, say "injured", you have to open every switch and decide what it does in each one. Forget one and the compiler won't tell you.

Step 3 of 9

One object per state

State puts each situation in its own object. In Java, the most natural way is an enum where each constant overrides the methods that concern it:

  • TRIAL lets you in while visits remain (and it's the only one that counts them), and renew() moves it to ACTIVE;
  • ACTIVE lets you in, freeze() returns FROZEN and expire(), EXPIRED;
  • FROZEN doesn't let you in, resume() goes back to ACTIVE and it can expire too;
  • EXPIRED doesn't let you in, and renew() goes back to ACTIVE.

Each method returns the next state: the transitions are written in the state itself.

Step 4 of 9

The membership delegates

Membership is the context: it's what the rest of the app uses. It has not a single if on its state: even the trial visits left are asked of the state. Every action does the same thing: it hands it to its current state and keeps the state that comes back.

state = state.freeze(this): if the membership is active, it becomes frozen; if it's on trial, the state refuses with an error. Membership doesn't need to know which of the two will happen.

Step 5 of 9

What isn't allowed, by default

Every action has a default behaviour: refuse it with a clear message ("can't freeze a trial membership"). That way each state only writes what it does allow.

checkIn is the exception: it's abstract, so every state is forced to decide whether it lets you in. If tomorrow you add a constant and forget, it won't compile.

Step 6 of 9

Ana freezes her membership

Ana goes on holiday:

  1. ana.freeze(): ACTIVE returns FROZEN.
  2. She tries to come in: FROZEN answers "membership is frozen: resume it first".
  3. She's back: ana.resume(), and FROZEN returns ACTIVE.
  4. She can come in again.

The example test does exactly this, and another one checks that a refused action doesn't change the state.

Step 7 of 9

Through the API

POST /api/memberships/1/freeze:

  1. MembershipService loads Ana's membership from the database, inside a transaction.
  2. It calls freeze(), and the ACTIVE state returns FROZEN.
  3. It saves the membership and answers 200 with the new state.

If she then tries to come in, POST /api/memberships/1/check-in answers 409 with the reason FROZEN gives.

Step 8 of 9

And Spring?

Spring's core doesn't ship a general State. What the app does need is to keep the state between requests, and that's where the enum helps:

  • the database only stores the name ("FROZEN");
  • when reading, MembershipState.valueOf(...) returns the constant, always the same object;
  • since a state holds no member data, every frozen membership shares the same FROZEN.

And Spring already treats enums by name in several places: Spring Data JDBC stores them with name(), and Spring MVC turns a URL parameter into the constant with valueOf (which is case-sensitive). With JPA, on the other hand, @Enumerated uses the position (ORDINAL) by default: always write @Enumerated(EnumType.STRING).

Step 9 of 9

Recap

You started with a switch on a String in every method and ended up with:

  • One state per situation, each with its rules and its transitions.
  • A context, Membership, that delegates without a single if.
  • A default behaviour that refuses what isn't allowed, and abstract for what must not be missing.
  • The state's name in the database.

Don't mix it up with Strategy: both put behaviour into interchangeable objects, but a strategy is picked by whoever uses it, whereas here it's the state itself that decides when to change to the next one.

And when you don't need it: with two states and one rule, an if reads better; and if there are many transitions that change often, a transition table (state and event, next state) makes them more visible.

Cheatsheet →

Code

SwitchingMembership.java

public void checkIn() {
    switch (status) {
        case "trial", "active" -> { /* come in (and trial visits? another field, another if) */ }
        case "frozen" -> throw new IllegalStateException("membership is frozen: resume it first");
        case "expired" -> throw new IllegalStateException("membership expired: renew it to come in");
        default -> throw new IllegalStateException("unknown status: " + status);
    }
}

public void freeze() {
    switch (status) {
        case "active" -> status = "frozen";
        case "trial", "frozen", "expired" -> throw new IllegalStateException("can't freeze a " + status + " membership");
        default -> throw new IllegalStateException("unknown status: " + status);
    }
}

public void resume() {
    switch (status) {
        case "frozen" -> status = "active";
        case "trial", "active", "expired" -> throw new IllegalStateException("can't resume a " + status + " membership");
        default -> throw new IllegalStateException("unknown status: " + status);
    }
}

SwitchingMembership.java

public void checkIn() {
    switch (status) {
        case "trial", "active" -> { /* come in (and trial visits? another field, another if) */ }
        case "frozen" -> throw new IllegalStateException("membership is frozen: resume it first");
        case "expired" -> throw new IllegalStateException("membership expired: renew it to come in");
        default -> throw new IllegalStateException("unknown status: " + status);
    }
}

public void freeze() {
    switch (status) {
        case "active" -> status = "frozen";
        case "trial", "frozen", "expired" -> throw new IllegalStateException("can't freeze a " + status + " membership");
        default -> throw new IllegalStateException("unknown status: " + status);
    }
}

public void resume() {
    switch (status) {
        case "frozen" -> status = "active";
        case "trial", "active", "expired" -> throw new IllegalStateException("can't resume a " + status + " membership");
        default -> throw new IllegalStateException("unknown status: " + status);
    }
}

MembershipState.java

TRIAL {
    @Override MembershipState checkIn(Membership m) {
        if (m.trialVisitsLeft() == 0) {
            throw new MembershipRuleException("trial used up: renew to keep training");
        }
        m.useTrialVisit();
        return this;
    }
    @Override int trialVisitsLeft(Membership m) {
        return Membership.TRIAL_VISITS - m.trialVisitsUsed();
    }
    @Override MembershipState renew(Membership m) { return ACTIVE; }
},
ACTIVE {
    @Override MembershipState checkIn(Membership m) { return this; }
    @Override MembershipState freeze(Membership m) { return FROZEN; }
    @Override MembershipState renew(Membership m) { return this; }
    @Override MembershipState expire(Membership m) { return EXPIRED; }
},
FROZEN {
    @Override MembershipState checkIn(Membership m) {
        throw new MembershipRuleException("membership is frozen: resume it first");
    }
    @Override MembershipState resume(Membership m) { return ACTIVE; }
    @Override MembershipState expire(Membership m) { return EXPIRED; }
},
EXPIRED {
    @Override MembershipState checkIn(Membership m) {
        throw new MembershipRuleException("membership expired: renew it to come in");
    }
    @Override MembershipState renew(Membership m) { return ACTIVE; }
};

Membership.java

public void checkIn() { state = state.checkIn(this); }
public void freeze()  { state = state.freeze(this); }
public void resume()  { state = state.resume(this); }
public void renew()   { state = state.renew(this); }
public void expire()  { state = state.expire(this); }

MembershipState.java

abstract MembershipState checkIn(Membership m);   // every state must decide this one
MembershipState freeze(Membership m) { return refuse("freeze"); }
MembershipState resume(Membership m) { return refuse("resume"); }
MembershipState renew(Membership m) { return refuse("renew"); }
MembershipState expire(Membership m) { return refuse("expire"); }
int trialVisitsLeft(Membership m) { return 0; }

private MembershipState refuse(String action) {
    String name = name().toLowerCase(Locale.ROOT);
    String article = "aeiou".indexOf(name.charAt(0)) >= 0 ? "an " : "a ";
    throw new MembershipRuleException("can't " + action + " " + article + name + " membership");
}

MembershipTest.java

Membership ana = new Membership(1, "Ana", MembershipState.ACTIVE, 0);

ana.freeze();                                       // ACTIVE → FROZEN
assertThatThrownBy(ana::checkIn).hasMessage("membership is frozen: resume it first");
ana.resume();                                       // FROZEN → ACTIVE
ana.checkIn();

MembershipApiTest.java

mvc.perform(post("/api/memberships/1/freeze"))
   .andExpect(status().isOk())
   .andExpect(jsonPath("$.state").value("FROZEN"));
mvc.perform(post("/api/memberships/1/check-in"))
   .andExpect(status().isConflict())
   .andExpect(jsonPath("$.error").value("membership is frozen: resume it first"));

MembershipRepository.java

public Optional<Membership> find(int id) {
    return jdbc.sql("select id, athlete, status, trial_visits from membership where id = ?")
        .param(id)
        .query((rs, n) -> new Membership(rs.getInt("id"), rs.getString("athlete"),
            MembershipState.valueOf(rs.getString("status")),        // "FROZEN" → MembershipState.FROZEN
            rs.getInt("trial_visits")))
        .optional();
}

/** Saves only if nobody changed the row since we read it (the values we read are the condition). */
public void save(Membership m, MembershipState readState, int readTrialVisits) {
    int rows = jdbc.sql("update membership set status = ?, trial_visits = ? "
            + "where id = ? and status = ? and trial_visits = ?")       // …and nobody changed it
        .params(m.state().name(), m.trialVisitsUsed(),                  // only the name is stored
                m.id(), readState.name(), readTrialVisits)
        .update();
    if (rows != 1) throw new ConcurrentChangeException();
}

Membership.java

public void checkIn() { state = state.checkIn(this); }
public void freeze()  { state = state.freeze(this); }
public void resume()  { state = state.resume(this); }
public void renew()   { state = state.renew(this); }
public void expire()  { state = state.expire(this); }

Quiz

1. Who decides which state an active membership moves to when it's frozen?

2. The box adds an INJURED state, left with resume(). What do you change?

3. Why can every frozen membership share the same FROZEN object?

4. What does MembershipRepository store in the status column?

Cheatsheet →

Run it