Skip to content

Hierarchical Traffic Light

A traffic light that demonstrates the core tradeoff in hierarchical state machines: you can model the same behavior with a flattened machine (all states at the top level, explicit transitions everywhere) or a nested machine (child states inherit transitions from parents via propagation).

In the nested variant, child states like Pedestrian.Walk and Pedestrian.Flashing automatically inherit the reset transition defined on their parent. You define shared behavior once on the parent, and it propagates down.

In the flattened variant, every state is a peer at the top level. Each state that needs to respond to reset must declare that transition explicitly. The machine is more verbose but immediately readable — no implicit inheritance to reason about.

Neither is universally better. Use nesting when you have genuine shared transitions across several child states. Use flat machines when clarity and explicitness matter more than concision.