Hierarchical state machine

Hierarchical state machines allows to group states together inside another state, each state can have any number of child states. This implies that states can be represented as a tree.

The fundamental benefit is that transitions can then be shared among states, transition duplication can then be eliminated. The "state explosion" problem can be avoided by using hierarchical state machines.

Let's have a look at the difference between a flat and a hierarchical state machine:

Flat state machine

Notice the the transition with the Stop() event in scattered around three state Washing, Rinsing and Spinning.

With a flat state machine, transitions must be added for each state, this leads to transition duplication and results in an error prone design.

Hierarchical state machine

To solve the problem related to flat state machine, let's create a new state called Running which will holds the three state Washing, Rinsing and Spinning. The state Running is called a composite state.

When the event Stop() is received, the machine goes to the state End if the current state is either Washing, Rinsing or Spinning.

Hierarchical state machine is part of the solution to implement large and maintainable state machines.