Dwarves
Memo
Type ESC to close search bar

Finite State Machine

A Finite State Machine is a model of computation based on a hypothetical machine made of one or more states. Only one single state of this machine can be active at the same time. It means the machine has to transition from one state to another in to perform different actions

Above image is a simple FSM, each circle is a state and arrow is an event or action.

Pros and Cons

Pros

Cons

Thinking in term of states (instead of transitions)

(Okay, tbh the concept of FSM is eye-opening for me :kappa:)

We will try to solve a very simple problem that we face everyday. We want to fetch data from a back-end API and display to the user

Before get into state machines, my workflow for building such a feature is something like this:

It seems pretty right for me, until there are a bunch of bugs coming because user dispatched an unexpected action

We will need to spend more effort to cover all these things that make our software much more complexity with a lot of business logic code also have to widen our testing cases

What if we think in the states way:

    When the user clicks the button, we are firing the request to the back end and then transition the machine to a “fetching” state.
    The data arrives successfully and is not corrupted. We use the data in some way and transition back to the “idle” state.

- failure

    If there is an error while making the request or parsing the data, we transition to an “error” state.

error: We show an error message and display the fetch-data button. This state accepts one action: retry: When the user clicks the retry button, we fire the request again and transition the machine to the “fetching” state.

This simplifies the logic and makes it more predictable. It also solves some of the problems mentioned above. Notice that, while we are in “fetching” state, we are not accepting any clicks. So, even if the user clicks the button, nothing will happen because the machine is not configured to respond to that action while in that state. This approach automatically eliminates the unpredictable branching of our code logic

Example