Skip to content

State machines and invalid-state prevention

Difficulty: Advanced

Key concepts

  • state machine
  • invalid state
  • std::variant
  • std::visit
  • transition table
  • late event
  • pure function
  • command
  • exhaustive testing
  • property-based test
  • How to count the states a class allows, compare them with the states the requirements mean, and remove the difference.
  • How to model each state as a type holding only its own data, in a std::variant, so that an impossible state cannot be written.
  • How to make the whole machine one pure function of a state and an event, which returns the next state and a command for the outside world, and why that makes it easy to test.
  • How to handle late events, such as a network reply or a timer that arrives after the state it was meant for has gone.
  • How to use a transition table as the specification, and test every state against every event.

A client program keeps one connection to a server. The requirements:

  • C1. On request, dial the server.
  • C2. If a dial fails, wait and dial again. The wait starts at 100 ms and doubles after each failure, up to 2 s. After 3 attempts in all, give up, go back to idle, and remember why. (With 3 attempts the waits are 100 ms and 200 ms; the 2 s cap matters if the number of attempts is raised.)
  • C3. If a working connection is lost, dial again at once, starting again from attempt 1.
  • C4. The connection can be closed at any time. Closing is final; a request to connect after closing is a mistake in the calling code.
  • C5. Replies from the network and timers can arrive late: a reply for an earlier attempt, or a timer started before a close. A late event must not change the state.
  • C6. A session that the server opened must never be leaked. If a dial succeeds when nobody wants the connection any more, hang it up.
  • C7. The rules must be testable without a network or a clock.

The first version kept a flag for each thing that might be true:

Every member function has to keep seven members consistent with each other, and the bug reports showed where it did not:

  • After close() during a dial, the dial’s success arrived and on_dial_succeeded set connected_ = true and stored the session. The object was now closed and connected, and the session was never hung up (C6).
  • A retry timer started before a successful reconnect fired later and started a second dial while connected (C5).
  • on_connection_lost forgot to reset retry_delay_, so a later failure waited 2 s on its first retry instead of 100 ms (C2).
  • Testing any of this needed a fake network and a fake clock, because the decisions and the calls to network_ were mixed in the same functions (C7).

Count the shapes the members allow. Three bools give 8 combinations. Each of the three std::optionals doubles that, so there are 64 shapes before counting the numbers in them. The requirements describe five states:

State What is true Data that exists only here Left by
Idle not connected, not trying why the last attempt gave up, if it did a connect request; a close
Connecting a dial is in progress which attempt this is (1, 2, or 3) the dial’s reply; a close
Connected a session is open the session losing it; a close
Waiting to retry a dial failed, and a timer is running which attempt failed; how long the wait is the timer; a close
Closed finished for good nothing nothing

Only six of the 64 shapes mean anything: one for each state, and two for Idle, with and without a reason. Every function in the flawed class had to avoid the other 58 by hand. “Closed and connected” is one of the 58, and that bug was a function that did not.

The fix is to choose a type that can hold only the five. A struct of members allows every combination of its members’ values, so the number of shapes is their product. A std::variant holds one of its alternatives, so the number of shapes is their sum. Each state is an alternative, and each alternative holds only that state’s data.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

connection.hpp
// The five states of the connection, one small struct each. Each state
// holds only the data that exists in that state, so a field that makes no
// sense there (a session while connecting, say) has nowhere to be stored.
// `bool operator==(...) const = default;` asks the compiler to write ==
// for us: it compares the members one by one, so tests can compare whole
// states with a single ==.
// Not connected and not trying. last_error is a std::optional<std::string>:
// empty after a normal start, or holding the reason if the last attempt
// used up its retries and gave up.
struct Idle {
std::optional<std::string> last_error; // set if the last attempt gave up
bool operator==(const Idle&) const = default;
};
// A dial is in progress. Only this state has an attempt in progress.
struct Connecting {
int attempt; // 1 for the first dial, 2 for the first retry, ...
bool operator==(const Connecting&) const = default;
};
// A session is open. Only this state has a session, so "closed but still
// holding a session" cannot be written.
struct Connected {
SessionId session;
bool operator==(const Connected&) const = default;
};
// A dial failed and a retry timer is running. It remembers which attempt
// failed (so a timer for an older attempt can be told apart) and how long
// the wait is.
struct WaitingToRetry {
int failed_attempt; // the attempt that failed; the next is one more
std::chrono::milliseconds delay; // a length of time in milliseconds
bool operator==(const WaitingToRetry&) const = default;
};
struct Closed { // final: nothing leaves it, and it carries no data
bool operator==(const Closed&) const = default;
};
// The state itself: a std::variant holds exactly ONE of the listed types
// at a time, and knows which one. So a State is Idle, or Connecting, or
// ..., never two at once. The order matters only for index(): Idle is
// alternative 0, Connecting 1, and so on up to Closed at 4.
using State = std::variant<Idle, Connecting, Connected, WaitingToRetry, Closed>;
  • The session exists only in Connected. “Closed with a session” cannot be written: Closed has no member to put it in.
  • The attempt number exists only where it means something: in Connecting, the attempt in progress, and in WaitingToRetry, the attempt that failed. Nothing has to reset it; leaving the state destroys it.
  • The reason for giving up lives in Idle, because that is the only state in which “why are we not connected?” has that answer.
  • Closed is empty and final. No function changes it into another state.
  • The defaulted == compares a state member by member, so a test can write step.next == State(Connecting{3}).

Not everything about the connection is state. The server’s address, or the retry policy, is the same in every state, so it belongs to the object that holds the state, not inside any alternative. A fact that is true in every state, or independent of the lifecycle, is an ordinary member.

State called a member function for each event. Here each event is a struct, and all of them are one more std::variant:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

connection.hpp
// What can happen. Each event is a plain struct (a value), so it can be
// stored, queued, logged, or replayed in a test. Replies from the network
// and timers carry the attempt or session they belong to, so a late one
// can be recognised: a reply whose number does not match the current
// state is old news.
struct ConnectRequested {}; // the user asked to connect; no data needed
struct DialSucceeded { // the network opened a session for a dial
int attempt; // which dial this reply belongs to
SessionId session; // the session the server opened
};
struct DialFailed { // the network could not connect for a dial
int attempt;
std::string reason; // kept in Idle if this was the last attempt
};
struct ConnectionLost { // an open session dropped
SessionId session; // which session dropped
};
struct RetryTimerFired {
int attempt; // the failed attempt the timer was started for
};
struct CloseRequested {}; // the user asked to close, for good
// One event of any of the six kinds, in this order: index 0 is
// ConnectRequested, up to 5 for CloseRequested.
using Event = std::variant<ConnectRequested, DialSucceeded, DialFailed, ConnectionLost,
RetryTimerFired, CloseRequested>;

An event as a value can be queued, logged, replayed in a test, or delivered from another part of the program, all without knowing the machine’s interface. The replies carry which attempt or which session they belong to. That is what makes C5 possible: if the network code ever delivers a reply for an attempt that is not in progress, such as DialFailed{1} while attempt 2 is in progress, it can be recognised and ignored. The advanced callout below says when that can happen.

The machine never dials, hangs up, or starts a timer itself. It returns a command that says what should happen, and the code that owns the network and the clock carries it out:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

connection.hpp
// What the machine asks the outside world to do. It never does it itself:
// it returns one of these, and the code that owns the network and the
// timers carries it out. That keeps the machine free of any network or
// clock, so it can be tested with plain values.
struct Dial { // start dialing; the reply will carry this attempt number
int attempt;
bool operator==(const Dial&) const = default;
};
struct StartRetryTimer { // wait `delay`, then deliver RetryTimerFired{attempt}
int attempt;
std::chrono::milliseconds delay;
bool operator==(const StartRetryTimer&) const = default;
};
struct CancelDial { // stop the dial in progress for this attempt
int attempt;
bool operator==(const CancelDial&) const = default;
};
struct HangUp { // close this session on the server, so it is not leaked
SessionId session;
bool operator==(const HangUp&) const = default;
};
// One command of any of the four kinds (index 0 is Dial, 3 is HangUp).
using Command = std::variant<Dial, StartRetryTimer, CancelDial, HangUp>;

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

connection.hpp
// What one event did, in one word. The tests check this as well as the
// next state, so "ignored" and "refused" are told apart.
enum class Verdict {
changed, // the state changed
unchanged, // the event was late, repeated, or had nothing to do here
rejected, // the caller asked for something impossible
};
// The whole result of one event: the state to move to (the same state if
// nothing changed), at most one command for the caller to carry out
// (std::nullopt when there is nothing to do), and the verdict.
struct Step {
State next;
std::optional<Command> command;
Verdict verdict;
};
// The numbers that tune retries. They are the same in every state, so
// they live outside the variant. The defaults give 3 attempts, waiting
// 100 ms after the first failure and 200 ms after the second.
struct RetryPolicy {
int max_attempts = 3; // after a failure of this attempt, give up
std::chrono::milliseconds first_delay{100};
std::chrono::milliseconds max_delay{2000};
// first_delay, doubled after each failure, but never more than max_delay.
// With the defaults: 1 gives 100 ms, 2 gives 200 ms, 5 gives 1600 ms,
// and 6 or more give 2000 ms.
[[nodiscard]] std::chrono::milliseconds delay_after(int failed_attempt) const;
};
// The whole state machine. A pure function: it reads its arguments and
// returns the result, with no side effects, so it is tested without a
// network or a clock. It takes everything by const reference (reads, no
// copy) and builds a brand-new Step; the `state` passed in is not changed.
[[nodiscard]] Step transition(const State& state, const Event& event, const RetryPolicy& policy);

transition is a pure function: its result depends only on its arguments, and calling it changes nothing. That is C7. A test passes a state and an event and looks at the Step; there is no network to fake and no clock to wait for. The Verdict says whether the state changed, whether the event was ignored, or whether the caller asked for something impossible (C4).

The connection's states, with each transition's event, guard, and command
Text description of the diagram

The machine starts idle. A connect request moves it from idle to connecting and dials attempt 1. From connecting, the reply for the attempt in progress moves it to connected if the dial succeeded. If it failed, it moves to waiting to retry and starts a retry timer when the attempt was below 3, or back to idle, remembering the reason, when it was attempt 3. When the retry timer for that attempt fires, it moves from waiting to retry back to connecting and dials the next attempt. From connected, losing the session moves it to connecting and dials attempt 1. A close request from idle, connecting, connected, or waiting to retry moves it to closed; from connecting it also cancels the dial, and from connected it hangs up the session. Closed is final. Every other event leaves the state as it is; a successful dial that is not wanted is hung up.

Diagram source (Mermaid)
stateDiagram-v2
[*] --> Idle
Idle --> Connecting : connect requested / dial 1
Connecting --> Connected : dial n succeeded
Connecting --> WaitingToRetry : dial n failed [n below 3] / start retry timer
Connecting --> Idle : dial n failed [n is 3] / remember why
WaitingToRetry --> Connecting : retry timer for n fired / dial n + 1
Connected --> Connecting : session lost / dial 1
Idle --> Closed : close requested
Connecting --> Closed : close requested / cancel dial
Connected --> Closed : close requested / hang up
WaitingToRetry --> Closed : close requested
Closed --> [*]

The diagram shows the transitions that change the state. The last sentence of its text is the one the flawed class got wrong, and the diagram does not draw it. The table does.

State machine diagrams filled in a table with one row per state and one column per event, so that every combination gets a decision. Here it is for the connection. “Same” means the state does not change.

State ↓ / Event → connect requested dial succeeded dial failed connection lost retry timer fired close requested
Idle Connecting 1, dial 1 same, hang up same same same Closed
Connecting n same if for n: Connected; else same, hang up if for n: Waiting n, start timer (or Idle after 3); else same same same Closed, cancel dial n
Connected s same same, hang up same if for s: Connecting 1, dial 1; else same same Closed, hang up s
Waiting n same same, hang up same same if for n: Connecting n + 1, dial; else same Closed
Closed rejected same, hang up same same same same

Each cell is a decision, and several were not obvious from the requirements:

  • A successful dial in any state except the right Connecting hangs up. The server has opened a session, and nobody else will close it (C6). This is the cell the “closed and connected” bug was in.
  • Close while waiting to retry sends no command. Cancelling the timer would be tidy, but it is not needed: when the timer fires, Closed ignores it. Fewer commands means fewer things that can go wrong in the code that carries them out. This assumes the timer code delivers into an object that is still alive: if the Connection is destroyed after closing, its timers must be cancelled first, or must not hold a reference to it.
  • Connect while connecting, connected, or waiting is ignored rather than rejected. A user who presses “connect” twice is not wrong.
  • Connect after close is rejected, because C4 says the caller is wrong. Close after close is ignored: closing twice is harmless.

One function, on, has an overload for each cell that does something. transition visits the state and the event together and calls the right one:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

connection.cpp
// One function for each cell of the table that does something. Overload
// resolution picks the most specific one for each state and event.
//
// Every `on` takes (the current state, the event, the retry policy) and
// returns a Step. A parameter with a type but no name, such as
// `const Idle&`, is one the function does not need to read: the type
// alone is what selects the overload. Two small helpers, defined just
// above, build the Step: changed(next, command) for a real change, and
// unchanged(state, command) to stay put. The command is optional in both,
// and leaving it out means "no command". Passing a Dial or a Connecting
// where a Command or a State is expected wraps it in the variant.
// Idle + connect: start the first attempt, and ask for its dial.
Step on(const Idle&, const ConnectRequested&, const RetryPolicy&) {
return changed(Connecting{1}, Dial{1});
}
// Connecting + a success: connected, but only if the reply is for the
// attempt in progress. A reply for another attempt is late; its session
// is real, though, so it is hung up instead of being forgotten.
Step on(const Connecting& now, const DialSucceeded& event, const RetryPolicy&) {
if (event.attempt != now.attempt) {
return unchanged(now, HangUp{event.session}); // a late reply: do not leak it
}
return changed(Connected{event.session});
}
// Connecting + a failure for the attempt in progress: give up after the
// last attempt, otherwise wait and retry. A failure for another attempt
// is late and changes nothing.
Step on(const Connecting& now, const DialFailed& event, const RetryPolicy& policy) {
if (event.attempt != now.attempt) {
return unchanged(now); // late: ignore it
}
if (now.attempt >= policy.max_attempts) {
return changed(Idle{event.reason}); // give up, and say why
}
// Not the last attempt: work out the wait (100 ms after attempt 1 with
// the defaults), remember it in the new state, and ask for a timer.
const auto delay = policy.delay_after(now.attempt);
return changed(WaitingToRetry{now.attempt, delay}, StartRetryTimer{now.attempt, delay});
}
// Close while a dial is in progress: closed, and cancel that dial.
Step on(const Connecting& now, const CloseRequested&, const RetryPolicy&) {
return changed(Closed{}, CancelDial{now.attempt});
}
// Connected + this session lost: dial again, counting from attempt 1.
// A loss report for some other (older) session is ignored.
Step on(const Connected& now, const ConnectionLost& event, const RetryPolicy&) {
if (event.session != now.session) {
return unchanged(now);
}
return changed(Connecting{1}, Dial{1}); // attempts start again at 1
}
// Close while connected: closed, and hang up the open session.
Step on(const Connected& now, const CloseRequested&, const RetryPolicy&) {
return changed(Closed{}, HangUp{now.session});
}
// Waiting + the timer for the attempt that failed: dial the next attempt.
// A timer started for some other attempt is old and ignored.
Step on(const WaitingToRetry& now, const RetryTimerFired& event, const RetryPolicy&) {
if (event.attempt != now.failed_attempt) {
return unchanged(now);
}
const int next = now.failed_attempt + 1;
return changed(Connecting{next}, Dial{next});
}
// Connect after close: the caller is wrong, so the verdict is rejected.
// The state is returned unchanged; Connection::handle turns this verdict
// into an exception.
Step on(const Closed& now, const ConnectRequested&, const RetryPolicy&) {
return Step{now, std::nullopt, Verdict::rejected};
}
Step on(const Closed& now, const CloseRequested&, const RetryPolicy&) {
return unchanged(now); // closing twice is harmless
}
// Close from any other state (Idle, WaitingToRetry): nothing to clean up.
// A retry timer that fires later meets Closed and is ignored.
// `template <typename S>` makes this one function for every state type S.
// The three states with their own close handler (Connecting, Connected,
// Closed) use those instead, because a plain function that matches
// exactly beats a template.
template <typename S>
Step on(const S&, const CloseRequested&, const RetryPolicy&) {
return changed(Closed{});
}
// A dial that succeeds when no dial is wanted (for example, after a
// close): hang up, or the session is never closed. This covers every
// state except Connecting, which has its own handler above.
template <typename S>
Step on(const S& now, const DialSucceeded& event, const RetryPolicy&) {
return unchanged(now, HangUp{event.session});
}
// Every other cell: the event is late or repeated, or means nothing here.
// It matches any state S and any event E, so it is the least specific
// overload: the compiler picks it only when nothing above fits.
template <typename S, typename E>
Step on(const S& now, const E&, const RetryPolicy&) {
return unchanged(now);
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

connection.cpp
Step transition(const State& state, const Event& event, const RetryPolicy& policy) {
// Visiting two variants calls the lambda with the current alternative
// of each, so `on` is chosen for this exact pair of types.
// The lambda's `const auto&` parameters make it a template: the
// compiler writes one version for each of the 5 x 6 = 30 pairs.
// [&policy] lets the lambda use `policy` by reference, without a copy.
// Whatever `on` returns, the lambda returns, and so does std::visit.
return std::visit([&policy](const auto& now, const auto& happened) {
return on(now, happened, policy);
}, state, event);
}
How this code works: transition and the on overloads

What happens when transition(state, event, policy) is called:

  1. std::visit looks inside both variants. It finds which alternative state holds (say Connecting) and which event holds (say DialFailed).
  2. It calls the lambda with those two objects, as a const Connecting& and a const DialFailed&. Inside the lambda the types are now known, so on(now, happened, policy) is an ordinary function call.
  3. The compiler has already chosen which on that call means, once for each of the 30 pairs, while compiling. The rules: a plain function that matches the exact types wins over any template; among templates, the one that names more exact types wins; the last template, which accepts anything, is used only when nothing else fits.
  4. The chosen on returns a Step, and the lambda and std::visit pass it straight back. Nothing has been changed anywhere: the caller decides what to do with the Step.

Some pairs, with the overload that runs and the Step it returns (using the default policy):

State Event on that runs Next state Command Verdict
Idle{} ConnectRequested{} (const Idle&, const ConnectRequested&) Connecting{1} Dial{1} changed
Connecting{2} DialFailed{2, "refused"} (const Connecting&, const DialFailed&) WaitingToRetry{2, 200ms} StartRetryTimer{2, 200ms} changed
Connecting{2} DialFailed{1, "timeout"} the same; the attempts differ Connecting{2} none unchanged
Idle{} CloseRequested{} template (const S&, const CloseRequested&) Closed{} none changed
Closed{} DialSucceeded{1, SessionId{18}} template (const S&, const DialSucceeded&) Closed{} HangUp{SessionId{18}} unchanged
Closed{} CloseRequested{} (const Closed&, const CloseRequested&), which beats both templates Closed{} none unchanged
Connected{SessionId{5}} RetryTimerFired{2} the catch-all (const S&, const E&) Connected{SessionId{5}} none unchanged

In the second row, attempt 2 is below max_attempts (3), so the machine retries, and delay_after(2) doubles the first delay of 100 ms once, to 200 ms. Had the state been Connecting{3}, the same handler would have returned Idle{"refused"} with no command.

How the right on is chosen:

  • std::visit with two variants calls the lambda with the alternative each one holds: a const Connecting& and a const DialFailed&, say. The compiler makes one version of the lambda for each of the 5 × 6 = 30 pairs of types, and in each one on(now, happened, policy) is an ordinary overloaded call with known types.
  • A non-template function that matches exactly is preferred over a template, so on(const Connecting&, const DialFailed&, ...) wins for that pair.
  • Between two templates, the more specialized one is preferred. For Idle and CloseRequested, both on(const S&, const CloseRequested&, ...) and on(const S&, const E&, ...) match, and the first is more specific. That is how “close from any other state” and “a late success from any other state” are written once.
  • The last template catches everything else and returns the state unchanged. Those are the “same” cells of the table.

Each handler for a reply or a timer checks the attempt or session first. A reply for an attempt that is no longer in progress is late, and is ignored, or hung up if it opened a session. That is C5 and C6 in one line each.

The describe functions use the other common form of std::visit: a set of lambdas, one per alternative, combined into one callable:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

connection.cpp
// A set of lambdas as one callable; the deduction guide is needed by
// Clang 14, which cannot deduce F... from the braces without it.
// `typename... F` is a pack: any number of types, here one per lambda.
// Overloaded inherits from every lambda type at once (`: F...`), and the
// `using` line brings each lambda's call operator into Overloaded, so all
// of them become overloads of one operator(). Calling it with an Idle then
// runs the lambda that takes `const Idle&`.
template <typename... F>
struct Overloaded : F... {
using F::operator()...;
};
// The deduction guide: "Overloaded built from lambdas of types F... is an
// Overloaded<F...>", so the caller never has to name the lambda types.
template <typename... F>
Overloaded(F...) -> Overloaded<F...>;

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

connection.cpp
// Turns a state into text for the example's output, such as
// "connecting (attempt 2)".
// No catch-all here: a new state that is not listed does not compile.
// Each lambda returns a std::string, so every branch has the same type.
std::string describe(const State& state) {
return std::visit(Overloaded{
// `s.last_error ?` asks "is there an error?" (an optional converts to
// true when it holds a value), and *s.last_error reads the string.
// std::string("idle") makes the other branch a std::string too.
[](const Idle& s) {
return s.last_error ? "idle (gave up: " + *s.last_error + ")" : std::string("idle");
},
[](const Connecting& s) { return "connecting (attempt " + std::to_string(s.attempt) + ")"; },
[](const Connected& s) {
return "connected (session " + std::to_string(s.session.value) + ")";
},
[](const WaitingToRetry& s) {
return "waiting " + ms(s.delay) + " after attempt " + std::to_string(s.failed_attempt);
},
[](const Closed&) { return std::string("closed"); },
}, state);
}

Overloaded inherits the call operator of every lambda it is built from, so overload resolution picks the lambda for the alternative the variant holds. C++20 lets the compiler deduce the template arguments of an aggregate like this one from its initializers. When we compiled it without the deduction guide, GCC 11.4 accepted it and Clang 14 did not, because Clang 14 does not implement that rule yet, so the guide stays. For describe, where every state needs its own text, no catch-all is the right choice.

Connection holds the current state and applies one event at a time:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

connection.hpp
// Holds the current state and applies events to it, one at a time. All
// the decisions are made by transition(); this class only stores the
// result and refuses events that transition() rejects.
class Connection {
public:
// `explicit` stops a RetryPolicy from turning into a Connection by
// accident. The policy is copied in (it is a few small numbers).
explicit Connection(RetryPolicy policy) : policy_(policy) {}
// Applies one event and returns the command the caller must carry
// out, if any. Throws std::logic_error for a rejected event, and
// leaves the state unchanged if anything throws.
[[nodiscard]] std::optional<Command> handle(const Event& event);
// A read-only view of the current state. The reference points into
// this object, so it is only good while the Connection lives, and it
// shows the new state after the next handle().
[[nodiscard]] const State& state() const noexcept { return state_; }
private:
RetryPolicy policy_;
State state_ = Idle{}; // every connection starts idle, with no error
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

connection.cpp
std::optional<Command> Connection::handle(const Event& event) {
// 1. Work out the whole result first, into a local Step. transition can
// throw (copying a string may run out of memory), but it only reads
// state_, so a throw here leaves the connection exactly as it was.
Step step = transition(state_, event, policy_); // may throw; state_ untouched
// 2. A rejected event is a bug in the caller: report it, change nothing.
if (step.verdict == Verdict::rejected) {
throw std::logic_error("rejected: " + describe(event) + " when " + describe(state_));
}
// 3. Commit. std::move lets state_ take over step.next's contents
// (such as the error string) instead of copying them.
state_ = std::move(step.next); // cannot throw: every state moves without throwing
// 4. Hand the command, if any, to the caller, who must carry it out.
return std::move(step.command);
}
  • Everything that can throw comes first. transition builds a complete new State, which can throw while copying a string, before state_ is touched.
  • The assignment cannot throw. Every alternative moves without throwing, so moving a State into state_ cannot throw either; a test checks that with static_assert(std::is_nothrow_move_assignable_v<State>). Together, these give handle the strong guarantee: if it throws, the state is what it was.
  • This also keeps the variant from becoming empty. When a std::variant is move-assigned from a variant that holds a different alternative, it destroys its old alternative and move-constructs the new one in its place. If building throws, the variant holds nothing, and valueless_by_exception() is true. A nothrow move cannot leave it there.
  • The caller carries out the command. handle returns it rather than doing it, so the class still has no network or clock in it. It is [[nodiscard]], because a dropped HangUp is a leaked session (C6).

The example drives one connection through a script of events, as a network and a timer would deliver them, including three that are repeated, late, or wrong:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// Plays a fixed list of events through one Connection and prints, for
// each one, the event, the command it produced (if any), and the state
// after it. There is no real network or timer: the script stands in for
// them, and the printed commands are what real code would carry out.
int main() {
using namespace conn;
Connection connection(RetryPolicy{}); // default policy: 3 attempts, from 100 ms
std::cout << "start: " << describe(connection.state()) << '\n';
// The events a real network and timer would deliver, in order. Each
// brace item builds one event struct, which is stored in the vector
// as an Event variant.
const std::vector<Event> script = {
ConnectRequested{},
DialFailed{1, "refused"}, // attempt 1 fails: wait, then retry
RetryTimerFired{1},
DialSucceeded{2, SessionId{17}},
ConnectRequested{}, // already connected: nothing to do
ConnectionLost{SessionId{17}},
CloseRequested{},
DialSucceeded{1, SessionId{18}}, // arrived after the cancel: hang it up
ConnectRequested{}, // closed for good: rejected
};
for (const Event& event : script) {
std::cout << describe(event) << '\n';
try {
// `if (const auto command = ...)` declares `command` (an optional
// Command) and tests it in one go: the body runs only when handle
// returned a command. *command reads the Command inside it.
if (const auto command = connection.handle(event)) {
std::cout << " do: " << describe(*command) << '\n';
}
} catch (const std::logic_error& error) {
// handle threw because the event was rejected; print why and go on.
std::cout << " " << error.what() << '\n';
}
std::cout << " now " << describe(connection.state()) << '\n';
}
}
Expected output
start: idle
connect requested
do: dial (attempt 1)
now connecting (attempt 1)
dial 1 failed (refused)
do: start retry timer, 100 ms (attempt 1)
now waiting 100 ms after attempt 1
retry timer for attempt 1 fired
do: dial (attempt 2)
now connecting (attempt 2)
dial 2 succeeded, session 17
now connected (session 17)
connect requested
now connected (session 17)
session 17 lost
do: dial (attempt 1)
now connecting (attempt 1)
close requested
do: cancel dial (attempt 1)
now closed
dial 1 succeeded, session 18
do: hang up session 18
now closed
connect requested
rejected: connect requested when closed
now closed

Reading the output:

  • The first dial fails, so the machine waits 100 ms and dials attempt 2, which succeeds with session 17.
  • “Connect requested” while connected changes nothing and asks for nothing.
  • When session 17 is lost, the machine dials again from attempt 1 (C3).
  • Closing during the dial cancels it. The cancel crossed with the dial’s success, which still arrives late (C5), and the machine asks for the new session 18 to be hung up (C6) instead of becoming connected.
  • Connecting after the close is rejected, and the state stays closed (C4).

The table above is the specification. The tests write it down again as data, from the diagram and the requirements, not by reading the code, and check the code against it. First, names for each alternative’s index, checked against the variants, and one sample of each state and event:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_transitions.cpp
// The index of each alternative, by name, checked against the variants.
// A variant numbers its alternatives from 0 in the order they are listed,
// and index() returns that number. The tests compare these numbers, so
// st::waiting reads better than a bare 3. Each small namespace (st, ev,
// cmd) keeps names such as `close` from clashing.
namespace st {
constexpr std::size_t idle = 0, connecting = 1, connected = 2, waiting = 3, closed = 4;
}
namespace ev {
constexpr std::size_t connect = 0, succeeded = 1, failed = 2, lost = 3, timer = 4, close = 5;
}
namespace cmd {
constexpr std::size_t dial = 0, start_timer = 1, cancel_dial = 2, hang_up = 3;
}
// static_assert is checked by the compiler: the build fails if it is
// false. std::variant_alternative_t<3, State> is "the type at index 3 of
// State", and std::is_same_v asks whether two types are the same. So if
// someone reorders a variant, these names stop compiling instead of
// silently pointing at the wrong alternative.
static_assert(std::is_same_v<std::variant_alternative_t<st::waiting, State>, WaitingToRetry>);
static_assert(std::is_same_v<std::variant_alternative_t<st::closed, State>, Closed>);
static_assert(std::is_same_v<std::variant_alternative_t<ev::timer, Event>, RetryTimerFired>);
static_assert(std::is_same_v<std::variant_alternative_t<ev::close, Event>, CloseRequested>);
static_assert(std::is_same_v<std::variant_alternative_t<cmd::hang_up, Command>, HangUp>);

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_transitions.cpp
// One sample of each state and each event, in variant order. The events
// carry the samples' attempt (2) and session (5), so each cell shows its
// main behavior; late events have their own tests.
// std::variant_size_v<State> is the number of alternatives (5 states, 6
// events), so the arrays have exactly one slot per alternative. Slot i
// must hold alternative i; the first test below checks that.
const std::array<State, std::variant_size_v<State>> states = {
Idle{}, Connecting{2}, Connected{SessionId{5}}, WaitingToRetry{2, 200ms}, Closed{},
};
const std::array<Event, std::variant_size_v<Event>> events = {
ConnectRequested{}, DialSucceeded{2, SessionId{9}}, DialFailed{2, "refused"},
ConnectionLost{SessionId{5}}, RetryTimerFired{2}, CloseRequested{},
};

Then the table, one row per cell:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_transitions.cpp
// The specification, copied from the state diagram: for each state and
// event, the state that follows, the verdict, and the command.
// States, events, and commands are written as indexes (st::, ev::, cmd::),
// which says which KIND of state or command is expected, not its data.
struct Row {
std::size_t state; // the sample state to start from
std::size_t event; // the sample event to apply
std::size_t next; // the kind of state expected after it
Verdict verdict; // changed, same, or rejected
std::optional<std::size_t> command; // the kind of command, or none
};
// Short names so that each row of the table fits on one line.
constexpr auto changed = Verdict::changed;
constexpr auto same = Verdict::unchanged;
constexpr auto rejected = Verdict::rejected;
constexpr auto none = std::nullopt;
// 30 rows: 5 states times 6 events. Read the first one as "Idle plus
// connect requested gives Connecting, changed, with a Dial command".
const std::vector<Row> table = {
{st::idle, ev::connect, st::connecting, changed, cmd::dial},
{st::idle, ev::succeeded, st::idle, same, cmd::hang_up},
{st::idle, ev::failed, st::idle, same, none},
{st::idle, ev::lost, st::idle, same, none},
{st::idle, ev::timer, st::idle, same, none},
{st::idle, ev::close, st::closed, changed, none},
{st::connecting, ev::connect, st::connecting, same, none},
{st::connecting, ev::succeeded, st::connected, changed, none},
{st::connecting, ev::failed, st::waiting, changed, cmd::start_timer},
{st::connecting, ev::lost, st::connecting, same, none},
{st::connecting, ev::timer, st::connecting, same, none},
{st::connecting, ev::close, st::closed, changed, cmd::cancel_dial},
{st::connected, ev::connect, st::connected, same, none},
{st::connected, ev::succeeded, st::connected, same, cmd::hang_up},
{st::connected, ev::failed, st::connected, same, none},
{st::connected, ev::lost, st::connecting, changed, cmd::dial},
{st::connected, ev::timer, st::connected, same, none},
{st::connected, ev::close, st::closed, changed, cmd::hang_up},
{st::waiting, ev::connect, st::waiting, same, none},
{st::waiting, ev::succeeded, st::waiting, same, cmd::hang_up},
{st::waiting, ev::failed, st::waiting, same, none},
{st::waiting, ev::lost, st::waiting, same, none},
{st::waiting, ev::timer, st::connecting, changed, cmd::dial},
{st::waiting, ev::close, st::closed, changed, none},
{st::closed, ev::connect, st::closed, rejected, none},
{st::closed, ev::succeeded, st::closed, same, cmd::hang_up},
{st::closed, ev::failed, st::closed, same, none},
{st::closed, ev::lost, st::closed, same, none},
{st::closed, ev::timer, st::closed, same, none},
{st::closed, ev::close, st::closed, same, none},
};

And two tests, one that the table is complete and one that the code agrees with it:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_transitions.cpp
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure
// if the condition is false, and LLD_CHECK_EQ(actual, expected) records a
// failure, printing both values, if they are not equal. They come from
// the site's small test header, lld_test.hpp.
// Proves the table is complete: every (state, event) pair appears exactly
// once, and the samples sit in variant order.
LLD_TEST(the_table_has_one_row_for_every_state_and_event) {
// A std::set keeps each value once, so a pair written twice is
// counted once.
std::set<std::pair<std::size_t, std::size_t>> cells;
for (const Row& row : table) {
LLD_CHECK(row.state < states.size() && row.event < events.size());
cells.insert({row.state, row.event});
}
LLD_CHECK_EQ(table.size(), states.size() * events.size());
// 30 rows and 30 different pairs: no pair twice, and since there are
// only 30 possible pairs, none is missing either.
LLD_CHECK_EQ(cells.size(), table.size()); // no pair twice, so none missing
// Sample i really is alternative i, so the indexes in the rows mean what
// the names say.
for (std::size_t i = 0; i < states.size(); ++i) {
LLD_CHECK_EQ(states[i].index(), i);
}
for (std::size_t i = 0; i < events.size(); ++i) {
LLD_CHECK_EQ(events[i].index(), i);
}
}
// Proves the code agrees with the table: runs transition on each row's
// sample state and event, and compares the kind of the result with the row.
LLD_TEST(every_state_and_event_behaves_as_the_table_says) {
const RetryPolicy policy;
std::string first_mismatch; // stays empty while everything matches
for (const Row& row : table) {
const Step step = transition(states[row.state], events[row.event], policy);
// Reduce the command to its index, or nothing, to match Row::command.
// step.command->index() reads index() of the Command inside the
// optional; `?:` picks that or std::nullopt.
const std::optional<std::size_t> command =
step.command ? std::optional(step.command->index()) : std::nullopt;
const bool matches =
step.next.index() == row.next && step.verdict == row.verdict && command == row.command;
if (!matches && first_mismatch.empty()) {
first_mismatch = name(row); // keep only the first, such as "state 4, event 5"
}
}
// Comparing with an empty string makes a failure print the bad cell.
LLD_CHECK_EQ(first_mismatch, std::string());
}
  • The completeness test checks that there are exactly states.size() * events.size() rows and no pair twice, so none is missing. Both sizes come from std::variant_size_v, so adding a state or an event makes the test fail until its rows are written. That is the failure the Ping experiment above produced.
  • The agreement test runs every cell and reports the first one that disagrees. To check that it can fail, we deleted the handler for close-after-close; the test failed and named “state 4, event 5”, the Closed row and CloseRequested column.
  • The table checks the kind of result (which state, which verdict, which command), not the data inside. The data has its own tests:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_transitions.cpp
// The table above checks only the kind of each result. This test follows
// one retry story and checks the data too: attempt numbers, the delay, the
// saved reason, and the session that is hung up. State(...) and Command(...)
// wrap one struct in the variant so it can be compared with ==.
LLD_TEST(the_data_carried_from_state_to_state_is_right) {
const RetryPolicy policy; // 3 attempts, 100 ms doubling to at most 2000 ms
// Attempt 2 fails: wait 200 ms (100 ms doubled once) before attempt 3.
Step step = transition(Connecting{2}, DialFailed{2, "refused"}, policy);
LLD_CHECK(step.next == State(WaitingToRetry{2, 200ms}));
LLD_CHECK(step.command == Command(StartRetryTimer{2, 200ms}));
// The timer for attempt 2 fires: dial attempt 3.
step = transition(WaitingToRetry{2, 200ms}, RetryTimerFired{2}, policy);
LLD_CHECK(step.next == State(Connecting{3}));
LLD_CHECK(step.command == Command(Dial{3}));
step = transition(Connecting{3}, DialFailed{3, "refused"}, policy); // the last attempt
LLD_CHECK(step.next == State(Idle{"refused"})); // gave up, and kept the reason
LLD_CHECK(!step.command); // no timer, no dial: nothing for the caller to do
step = transition(Connected{SessionId{5}}, CloseRequested{}, policy);
LLD_CHECK(step.command == Command(HangUp{SessionId{5}}));
}
// Every event here belongs to an older attempt or session than the state
// expects (the samples in the table never do). Each must leave the state
// alone, and the late success must still be hung up.
LLD_TEST(late_replies_and_timers_are_ignored_or_cleaned_up) {
const RetryPolicy policy;
const State dialing_2 = Connecting{2};
// A failure for attempt 1 while attempt 2 is in progress: ignored.
Step step = transition(dialing_2, DialFailed{1, "timeout"}, policy);
LLD_CHECK(step.next == dialing_2 && step.verdict == Verdict::unchanged && !step.command);
// A success for attempt 1: the state stays, but session 8 is hung up.
step = transition(dialing_2, DialSucceeded{1, SessionId{8}}, policy);
LLD_CHECK(step.next == dialing_2);
LLD_CHECK(step.command == Command(HangUp{SessionId{8}}));
// Session 4 lost while connected on session 5: not ours, ignored.
step = transition(Connected{SessionId{5}}, ConnectionLost{SessionId{4}}, policy);
LLD_CHECK(step.next == State(Connected{SessionId{5}}) && step.verdict == Verdict::unchanged);
// The timer for attempt 1 while waiting after attempt 2: ignored.
step = transition(WaitingToRetry{2, 200ms}, RetryTimerFired{1}, policy);
LLD_CHECK(step.next == State(WaitingToRetry{2, 200ms}) && !step.command);
}

The samples’ events all match the samples’ attempt and session, so the table covers each cell’s main behavior; the late-event test covers the other branch of every cell that checks.

A table checks one step at a time. Some rules are about sequences, such as “nothing ever leaves Closed” or “no session is ever leaked”. A test can check those after every step of many random sequences:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_properties.cpp
// Instead of chosen cases, this test plays 200 runs of 50 random events
// each, starting from Idle every run, and after every step checks four
// rules that must hold whatever happened before. random_event (above,
// not shown) picks one of the six events, with attempts from 1 to 3, a
// new session for each success, and a loss for one of the last four
// sessions.
LLD_TEST(random_event_sequences_keep_the_rules) {
// std::mt19937 is a standard pseudo-random number generator. Starting
// it from the same number (the seed) gives the same sequence each time.
std::mt19937 random(2026); // a fixed seed, so a failure can be repeated
const RetryPolicy policy;
std::uint64_t last_session = 3; // random_event adds 1 for each new session
for (int run = 0; run < 200; ++run) {
State state = Idle{};
for (int i = 0; i < 50; ++i) {
const Event event = random_event(random, last_session);
const Step step = transition(state, event, policy);
// The rules below look at the state before (state), the event,
// and the step's result; the step is applied at the loop's end.
// Nothing leaves Closed.
if (std::holds_alternative<Closed>(state)) {
LLD_CHECK(std::holds_alternative<Closed>(step.next));
}
// An attempt number stays within the policy.
// std::get_if<Connecting>(&v) returns a pointer to the Connecting
// inside v if v holds one, or nullptr if it holds anything else.
// Declaring it inside `if (...)` runs the body only when it is
// not null, so `dialing->attempt` is always safe here.
if (const auto* dialing = std::get_if<Connecting>(&step.next)) {
LLD_CHECK(dialing->attempt >= 1 && dialing->attempt <= policy.max_attempts);
}
// Only a change changes the state.
if (step.verdict != Verdict::changed) {
LLD_CHECK(step.next == state);
}
// Every session that opens is either used or hung up, never leaked.
if (const auto* opened = std::get_if<DialSucceeded>(&event)) {
const bool used = step.next == State(Connected{opened->session});
const bool hung_up = step.command == Command(HangUp{opened->session});
// != between two bools means "exactly one of them is true":
// not neither (a leak), and not both (connected, yet hung up).
LLD_CHECK(used != hung_up);
}
state = step.next; // apply the step and go on to the next event
}
}
}
  • The seed is fixed, so the test makes the same sequences every time it runs with the same standard library, and a failure can be repeated. (std::mt19937 gives the same numbers everywhere, but std::uniform_int_distribution may turn them into different values on another library.)
  • Each property is checked after every step: 10,000 steps here.
  • Random events are not a proof. They only reach the states the generator happens to reach, and a rule that needs a long, exact sequence may never be tested. The table is what guarantees every cell is checked once; the random test adds sequences nobody wrote by hand. Property-based and table-driven tests goes further.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_transitions.cpp
// A compile-time check that moving one State into another cannot throw.
// Connection::handle relies on it: its last step must not fail half way.
static_assert(std::is_nothrow_move_assignable_v<State>);
// Proves the strong guarantee for a rejected event. LLD_CHECK_THROWS(
// expression, type) fails unless the expression throws that type.
LLD_TEST(a_rejected_event_throws_and_changes_nothing) {
Connection connection{RetryPolicy{}};
// Close from Idle: allowed, and there is nothing to clean up.
LLD_CHECK(connection.handle(CloseRequested{}) == std::nullopt);
// Connect after close is rejected, so handle throws ...
LLD_CHECK_THROWS(connection.handle(ConnectRequested{}), std::logic_error);
// ... and the state is still Closed afterwards.
LLD_CHECK(connection.state() == State(Closed{}));
}

When the states carry no data and the transitions have no guards, the table itself can be the implementation: an array indexed by state and event.

// Three states and two events, with no data and no conditions.
enum class Light { red, green, yellow };
enum class Signal { timer, emergency };
// The whole table as a 3 x 2 array: row = current light, column = signal.
// Each entry is the light that comes next.
constexpr Light next[3][2] = {
// timer emergency
{Light::green, Light::red}, // red
{Light::yellow, Light::red}, // green
{Light::red, Light::red}, // yellow
};
// static_cast<int> turns each enumerator into its position (red is 0,
// green 1, yellow 2; timer 0, emergency 1), which is used as the index.
// So step(Light::green, Signal::timer) reads next[1][0], Light::yellow.
Light step(Light now, Signal signal) {
return next[static_cast<int>(now)][static_cast<int>(signal)];
}

This code is illustrative and was not compiled.

That is compact, and every cell is visible on one screen. It is not checked, though: a row with a missing initializer still compiles, and the missing cell silently becomes Light::red, the first enumerator. A test that checks every cell is still needed. It fits lexers, protocol parsers, and simple device modes. It stops fitting as soon as a state carries data (the attempt number), a transition has a guard (“if below 3”), or a transition does something (dial). Each cell then needs a function, and the table becomes an array of function pointers that is harder to read than the overloads above. The connection is on the far side of that line.

class conn::Connection

holds the state; one thread at a time

Data members

  • RetryPolicy policy_;
  • State state_; starts as Idle

Member functions

  • explicit Connection(RetryPolicy policy);
  • [[nodiscard]] std::optional<Command> handle(const Event& event); strong; throws std::logic_error if rejected
  • const State& state() const noexcept;

class conn::Step

what one event does

Member functions

  • State next;
  • std::optional<Command> command;
  • Verdict verdict; changed, unchanged, or rejected

class conn::RetryPolicy

3 attempts, 100 ms doubling to 2 s

Member functions

  • int max_attempts;
  • std::chrono::milliseconds delay_after(int failed_attempt) const;

class conn::State

a std::variant; each state holds only its own data

Member functions

  • Idle{optional last_error} or Connecting{attempt} or Connected{session}
  • or WaitingToRetry{failed_attempt, delay} or Closed{}

class conn::Event

a std::variant; replies say which attempt or session

Member functions

  • ConnectRequested or DialSucceeded{attempt, session} or DialFailed{attempt, reason}
  • or ConnectionLost{session} or RetryTimerFired{attempt} or CloseRequested

class conn::Command

a std::variant; carried out by the caller

Member functions

  • Dial{attempt} or StartRetryTimer{attempt, delay} or CancelDial{attempt} or HangUp{session}
The connection state machine; the states, events, and commands are summarized

The free function Step transition(const State&, const Event&, const RetryPolicy&) is the whole machine; Connection only stores its result.

When this design fits, and when it does not

Section titled “When this design fits, and when it does not”

It fits when:

  • States carry different data. That is where a struct of members allows shapes that mean nothing, and a variant does not.
  • Events come from outside, at times the code does not control: networks, timers, users, hardware. Late and repeated events are normal there, and each one needs a decision.
  • The rules matter enough to test exhaustively: payments, connections, devices, workflows with money or safety attached.

It is more than you need when:

  • There are two states and no data. A bool, or a std::optional, is a state machine already.
  • The “states” are really independent facts. A connection that is connected or not, and separately compressed or not, has four valid combinations, all meaningful. A product of members is right for independent facts; a variant is for facts that exclude each other.
  • Each state’s rules are long. When a state needs many lines for each event, the state classes of State keep a state’s rules together and may read better than one overload per cell.
  • A flag next to the variant. Adding bool is_connected_ “for speed” brings back a second copy of the truth that can disagree. Ask the variant: std::holds_alternative<Connected>(state_).
  • std::get without checking. std::get<Connected>(state_) throws std::bad_variant_access if the state is anything else. Use std::get_if, or std::visit, which cannot pick the wrong one.
  • Events with no identity. A DialFailed that does not say which attempt failed cannot be told apart from a late one (C5).
  • Doing the work inside the transition. A transition that dials the network cannot be tested without one, and a dial that throws half way leaves the state and the world disagreeing. Return a command.
  • Keeping a reference into the variant across an assignment. A Connecting* from std::get_if points into state_; after state_ = ... it dangles if the alternative changed, and sees a different value if it did not. Either way, look it up again. State showed the same trap.
  • Putting shared data in every state. If each alternative carries the server address, every transition has to copy it across, and one will forget. Data that is the same in every state belongs to the holder.
  • A catch-all with no table test, which makes every new event silently ignored.
  • “Retry now” while waiting. WaitingToRetry with ConnectRequested becomes Connecting n + 1 and a dial. The old timer for n is still pending. Usually it will not match when it fires, but after a lost connection the numbers start again, and it can match a new WaitingToRetry for the same n and skip that wait. So this change must also cancel the timer, with a new CancelRetryTimer command, or give each timer an id that never repeats. Add the handler and the command, and change one row of the table.
  • A heartbeat. Connected gains a last_heard time, and a HeartbeatMissed event joins Event. The compiler stops at describe(const Event&), and the table test fails until five new rows are written, one for each state.
  • A TLS handshake between connecting and connected. That is a new state, Handshaking, with its own data (the session and the attempt). describe(const State&) stops compiling until it has a case, and the table test fails until six new rows are written, one for each event.
  • Duplicate replies from a new network layer. The attempt number is no longer enough to recognise a late reply (see the advanced callout above). Give each dial an id that never repeats.
  • Several threads deliver events. Connection is not thread safe, and the order of events matters. Deliver them through one queue that one thread drains, as Asynchronous work, cancellation, and shutdown describes.

Exercise: Remove an impossible state

A file upload is tracked by this class:

struct Upload {
bool started = false;
bool finished = false;
bool failed = false;
int percent = 0; // 0 to 100 while uploading
std::optional<std::string> url; // set when finished
std::optional<std::string> error; // set when failed
int retries_left = 3; // goes down on each failure
};

This code is illustrative and was not compiled.

  1. How many shapes do the three bools and two std::optionals allow? List three combinations that mean nothing.
  2. Rewrite the state as a std::variant in which none of them can be written.
  3. Where does retries_left go, and why?
Show the explained answer

1. 2 × 2 × 2 × 2 × 2 = 32 shapes, before counting percent and retries_left. Three that mean nothing:

  • finished and failed both true.
  • finished true but url empty, or url set while not finished.
  • url and error both set.

Others: failed with no error; finished without started; and, counting percent, started false but percent at 40.

2. Four states, each with only its own data:

struct Pending {};
struct Uploading {
int percent; // 0 to 100
};
struct Done {
std::string url;
};
struct Failed {
std::string error;
};
using UploadState = std::variant<Pending, Uploading, Done, Failed>;

These types, with a small class that uses them, were compiled as a separate file with GCC 11.4 and Clang 14. Now the URL exists only when the upload is done, the error only when it failed, and the percentage only while uploading. Nothing can be both done and failed. percent still has a rule, 0 to 100, which a type could check once, as in Strong types and API contracts.

3. retries_left is not part of any one state: it counts failures across the whole upload, and it has to survive moving from Failed back to Uploading. If it lived in Failed, every retry would have to copy it into Uploading and back. It belongs to the class that holds the state, next to it:

class Upload {
UploadState state_ = Pending{};
int retries_left_ = 3; // counts across attempts, in every state
};

That class was part of the compiled file. A fact that is the same kind of fact in every state is ordinary data, not state.

  • Count the shapes a class’s members allow and compare them with the states the requirements mean. The difference is the impossible states, and every function has to avoid them by hand.
  • A struct of members allows every combination; a std::variant allows one of its alternatives. Give each state a struct with only its own data, and the impossible states cannot be written.
  • Make events and commands values too. Then the whole machine is one pure function from a state and an event to the next state and a command, and it can be tested without a network or a clock.
  • Events from outside can be late. Make them say which attempt or session they belong to, decide what each late event does, and clean up anything a late success opened.
  • Apply a step with the strong guarantee: build the new state first, then move it in with an assignment that cannot throw.
  • Write the table of every state against every event, and test the code against it, with a check that the table has a row for every pair. Add properties over random sequences for the rules that span many steps.