Hierarchical state machines
Nested states, entry and exit actions, and statecharts.
When flat machines repeat themselves
Flat state machines suffer from a specific kind of growth: the same transition appears in many states. A media player's POWER_OFF button must work in PLAYING, PAUSED, SEEKING, BUFFERING and MENU. A device's FAULT event must be handled in every operational state. Copying the transition into each state is tedious and easy to get wrong when a new state is added.
A hierarchical state machine (HSM), the model behind UML statecharts and David Harel's original statecharts, lets states contain sub-states. A sub-state that does not handle an event passes it to its parent.
+-------------------------- ON ---------------------------+
| POWER_OFF -> OFF (handled once, here) |
| |
| +--------- ACTIVE ----------+ +-- MENU --+ |
| | PLAYING <---> PAUSED | <----> | | |
| +---------------------------+ +----------+ |
+----------------------------------------------------------+
OFF
PLAYING handles PAUSE; it does not mention POWER_OFF at all. When POWER_OFF arrives in PLAYING, it is not handled there, so it goes up to ACTIVE, then to ON, which handles it.
Behavioural inheritance
This is behavioural inheritance: a sub-state inherits all of its parent's behaviour and only specifies what is different, exactly like a subclass overriding methods. Benefits:
- Common transitions (power off, fault, timeout, disconnect) are written once.
- Adding a new sub-state automatically gets the common behaviour.
- The diagram shows structure at several levels of detail.
Entry and exit actions in a hierarchy
When a transition crosses levels, exit actions run from the innermost current state outwards up to (but not including) the least common ancestor of source and target, then entry actions run from just below that ancestor inwards down to the target.
For a transition from PLAYING to MENU (both inside ON):
- exit
PLAYING - exit
ACTIVE - enter
MENU
ON is neither exited nor entered, because the transition stays within it. This is what makes hierarchy powerful for resources: ON's entry action powers the display, its exit action turns it off, and no transition inside ON touches it.
#include <stdio.h>
/* A tiny HSM: each state knows its parent; the dispatcher walks up until someone handles the event. */
typedef enum { S_TOP, S_OFF, S_ON, S_ACTIVE, S_PLAYING, S_PAUSED, S_MENU, S_COUNT } st_t;
typedef enum { E_POWER, E_PLAY, E_PAUSE, E_MENU, E_BACK } ev_t;
static const st_t parent[S_COUNT] = { S_TOP, S_TOP, S_TOP, S_ON, S_ACTIVE, S_ACTIVE, S_ON };
static const char *const name[S_COUNT] = { "top", "OFF", "ON", "ACTIVE", "PLAYING", "PAUSED", "MENU" };
static st_t current = S_OFF;
/* Returns the target state if `s` handles `e`, or S_COUNT if it passes the event to its parent. */
static st_t handler(st_t s, ev_t e) {
switch (s) {
case S_OFF: return e == E_POWER ? S_PAUSED : S_COUNT;
case S_ON: return e == E_POWER ? S_OFF : S_COUNT; /* handled once for all sub-states */
case S_ACTIVE: return e == E_MENU ? S_MENU : S_COUNT;
case S_PLAYING: return e == E_PAUSE ? S_PAUSED : S_COUNT;
case S_PAUSED: return e == E_PLAY ? S_PLAYING : S_COUNT;
case S_MENU: return e == E_BACK ? S_PAUSED : S_COUNT;
default: return S_COUNT;
}
}
static int depth(st_t s) { int d = 0; while (s != S_TOP) { s = parent[s]; d++; } return d; }
static void transition(st_t target) {
/* find the least common ancestor of current and target */
st_t a = current, b = target;
while (depth(a) > depth(b)) a = parent[a];
while (depth(b) > depth(a)) b = parent[b];
while (a != b) { a = parent[a]; b = parent[b]; }
st_t lca = (current == target) ? parent[current] : a;
for (st_t s = current; s != lca; s = parent[s]) printf(" exit %s\n", name[s]);
st_t path[S_COUNT]; int n = 0;
for (st_t s = target; s != lca; s = parent[s]) path[n++] = s;
while (n > 0) printf(" enter %s\n", name[path[--n]]);
current = target;
}
static void dispatch(ev_t e, const char *label) {
printf("%s in %s:\n", label, name[current]);
for (st_t s = current; s != S_TOP; s = parent[s]) {
st_t target = handler(s, e);
if (target != S_COUNT) { transition(target); return; }
}
printf(" ignored\n");
}
int main(void) {
dispatch(E_POWER, "POWER");
dispatch(E_PLAY, "PLAY");
dispatch(E_MENU, "MENU");
dispatch(E_POWER, "POWER");
return 0;
}
Notice the second POWER arrives in MENU, which knows nothing about power; ON handles it and every state from MENU up to ON is exited.
Initial transitions and history
- Initial transition: entering a composite state must end in one of its leaf sub-states; each composite state names a default (
ACTIVEstarts inPAUSED). - History: a composite state can remember which sub-state it was last in, so returning from
MENUresumesPLAYINGorPAUSEDas appropriate. Shallow history remembers one level; deep history remembers the full nested configuration.
Guards, orthogonal regions and other statechart features
UML statecharts add more:
- Orthogonal regions: a state containing two independent sub-machines active at the same time (a phone's call state and its battery state). Often simpler to implement as two separate machines.
- Deferred events: a state can hold an event to be processed after the next transition.
- Internal transitions: handle an event without exiting and re-entering the state (no exit/entry actions run).
Implementations
- QP/C and QP/C++ (Quantum Leaps): a widely used open-source framework implementing HSMs as active objects, with a graphical modelling tool (QM) that generates code. Its
Q_SUPER()/Q_HANDLED()/Q_TRAN()return convention is the same parent-delegation idea as the example above. - Code generators: Yakindu/itemis CREATE, Stateflow (Simulink), IBM Rhapsody; common in automotive and safety work.
- Hand-written: the parent-table approach above scales to dozens of states.
When not to bother
If no transitions repeat and the machine has fewer than about eight states, a flat machine is simpler. Introduce hierarchy when you notice the same event handled identically in many states, or entry and exit actions duplicated across siblings.
Pitfall: Deep hierarchies make the path of an event harder to follow. Keep nesting to two or three levels and log every transition with the exit and entry sequence.
Interview question: What problem do hierarchical state machines solve, and what is behavioural inheritance?
Answer: Flat machines duplicate transitions that are common to many states, such as power off, fault or disconnect handlers, and the duplication grows with every new state. In an HSM, states are nested and an event not handled by the current state is passed to its parent, so common behaviour is defined once in a superstate and sub-states define only their differences. That is behavioural inheritance, analogous to subclasses inheriting and overriding methods. Nested entry and exit actions also manage resources cleanly at the right level.
Interview question: In which order do exit and entry actions run for a transition between two nested states?
Answer: Find the least common ancestor (LCA) of the source and target. Exit actions run from the current innermost state outwards up to, but not including, the LCA. Then entry actions run from the state just below the LCA inwards down to the target, followed by any initial transitions into the target's default sub-states. States that contain both source and target are not exited or entered.
Build it: one fault rule for every state
This is step 4, the last of the module project. As the charger grew, the same rows kept appearing in every state: "on a fault, go to FAULT", "on unplug, go back to IDLE". A hierarchical state machine writes such a rule once, in a parent state, and every child inherits it.
Lab: A hierarchical state machine with inherited events
The states now form a tree:
ROOT, the top: handlesEV_FAULT(go toFAULT).IDLE: handlesEV_PLUG(go toPLUGGED).ACTIVE, a car is connected: handlesEV_UNPLUG(go toIDLE).PLUGGED: handlesEV_CARD_OK(go toCHARGING).CHARGING: handlesEV_FULL(go toDONE) andEV_UNPLUG(go toFAULT: pulled out while live). Its ownEV_UNPLUGrow overrides the one inACTIVE.DONE: no rows of its own.FAULT: handlesEV_RESET(go toIDLE), andEV_FAULT(stay, doing nothing), so a repeated fault does not leave and re-enter it.
The table of rows and the tree (PARENT[]) are provided. Write hsm_dispatch(e):
- Look for a row for
ein the current state; if there is none, in its parent, then its parent's parent, up toROOT. If no state handles it, ignore it. - If the row's target is the current state, do nothing more.
- Otherwise, exit from the current state upwards until reaching the lowest common ancestor of the current state and the target (it is not exited), then enter downwards from just below it to the target. Call
on_exit(s)andon_entry(s)for each state on the way (they print what happens), and finally make the target the current state.
From CHARGING to DONE, only CHARGING is exited and DONE entered, because both are inside ACTIVE. From CHARGING to FAULT, CHARGING and then ACTIVE are exited, then FAULT is entered.
Going deeper
Interview question: How would you structure a drone's flight modes so 'low battery: land now' applies in every mode?
Answer: Put the flight modes (manual, position hold, waypoint mission) inside a parent 'flying' state that handles the battery-critical and lost-link events once, for all of them, by transitioning to an emergency-land state. Children handle only what differs. Hierarchical state machines remove the copy-paste that makes such rules inconsistent.
Interview question: What is an orthogonal region in a statechart, and how is it usually implemented in C?
Answer: A composite state containing two or more independent sub-machines active at the same time, such as a device's connection state and its battery state, which would otherwise multiply into every combination of states. In C it is usually implemented as separate state machines (often separate active objects) that each receive the relevant events, which is simpler and keeps them independent.
Interview question: What is a history pseudo-state?
Answer: A marker in a composite state that remembers which sub-state was active when the composite was last exited, so a transition back into the composite resumes there instead of at the default initial sub-state. Shallow history remembers one level, deep history the full nested configuration. A pause-and-resume feature is the classic use.
Explain it: In your own words, explain how a hierarchical state machine avoids repeating the same transition in many states.
Answer: States are nested inside parent states. When an event arrives, the current innermost state gets the first chance to handle it; if it does not, the event is passed to its parent, then the grandparent, and so on. A transition that applies to many states, such as power off or a fault, is therefore defined once in a common parent and every sub-state inherits it automatically, including sub-states added later. Sub-states only describe what differs from their parent, like subclasses overriding methods.