06 August 2018 / 10 minute read
Parallel States
Learn to use parallel states to model independent behaviors within a single system.
Consider a hotel room that has both a room light and a desk lamp, each of which may be turned on or off independently. How can we model this behavior?
Well, if only one state can be active at any given time, we need to list out all possible permutations. Doing so gives states like “Room light on, desk light off” and “Room light on, desk light on”. With just two lights, there are only four permutations — not so bad.
But as the number of lights in the room increase, we’ll need exponentially more states — not a great situation. What’s worse, the state names become increasingly long (to describe all of the lights) and couple what are, arguably, completely independent things (the status of the room light has no bearing on a desk lamp’s behavior). This makes for a tangled, confusing, and large spec that communicates poorly.
How can we do better?
Introducing parallel states
We can resolve this dilemma by introducing a new kind of parent state: A parallel state. (See the five minute introduction for a background on parent states / hierarchy.)
Unlike a regular parent state, which has only one child active at a time, if any of a parallel state’s children is active, then all of its children are active.
And, since each child can respond to events in the usual way, parallel states allow us to model multiple, independent behaviors.
For example, we can describe our hotel room lights more clearly using a parallel state (indicated by a &
suffix):
Now, the room and desk lights can be modeled clearly as independent states, and both can respond to their respective switch events.
More complex parallelism
Parallel states can exist anywhere, not just at the top-level.
For example, we can design more elaborate hotel room lighting that only allows the lights to function when a the room key is inserted in a slot near the door. (This is a common design in Japanese and European hotels; it ensures that lights can’t be left on after the guest has exited their room — assuming they remember to take their key!)
We can do this by making the Hotel Room state a regular state, introducing two children, “Power Off” and “Power On”, and making the latter a parallel state to allow for independent operation of the lights:
Further examples and reading
- See the Font Style Selector, which uses parallel states to model whether text should be bold, italic, and/or underlined (and includes a clickable prototype!)