Course lesson

Replace Enumerated States with a State Machine

Enumerating the possible states of a function is a sound way to write a function, but it is imperative and could benefit from abstraction. We can do this with a state machine.

Duration
3 min
Access
Pro
Transcript
Available

Enumerating the possible states of a function is a sound way to write a function, but it is imperative and could benefit from abstraction. We can do this with a state machine.

A state machine formalizes how we enumerate states and transitions. For the sake of clarity and to emphasize the core concepts, I will be overly verbose with my code in this lesson.

In this lesson, we'll replace the state enum with individual state objects. We'll also replace our events toggle() and break() with events TOGGLE and BREAK. I'll also demonstrate the usefulness of the Machine's initialState getter and the transition method. Lastly, I'll show what happens when we pass erroneous states or events into our machine.