State Machines: Understanding the Problem

In his Frontend Masters course on state machines, David Khourshid explains that people typically write code “bottom up”.

What is bottom up code? Here’s an example:

We have a button that fetches some data when clicked. If we click it once, it should be disabled until the data is fetched. So we put this logic in the event handler for the button. It looks something like:


const elButton = document.querySelector('#button');

elButton.addEventListener('click', () => {
  elButton.setAttribute('disabled', 'true');
  console.log('Loading data...', Date.now());
});

This is a problem because the logic for our application gets spread around all these event handlers.

Bottom-up code is:

  • Difficult to test

  • Difficult to understand

  • Guaranteed to contain bugs

  • Difficult to add features to because it will interfere with other code

  • More features make the problem worse (“combinatorial explosion”)


So we need a way to control this explosion of complexity. This is where state machines can help.

In future posts, I’ll share my notes on this topic as I continue to go through David’s course.