Skip to main content

Untangling your Logic using State Machines

Updated 8 min readMarkdown
Untangling your Logic using State Machines

You may find this article useful if:

Introduction

A few weeks ago, I was working on a Smart TV application where I had to control a button's visibility in a video player. Although the logic seemed complex at first due to the different states of the application, I had the following pointers:

  • My button could be either visible or invisible.
  • If any key was pressed while my button was invisible, it would become visible without triggering the action connected to the button.
  • When my button became visible, a 3-second timer would start.
  • If the timer expired, the button would then become invisible.
  • if a key was pressed while my button was visible, the timer would restart.

After seeing this logic, I decided to create the following diagram to describe it:

Diagram of the states that were previously described. There's two circles, one for "visible", the other one for "invisible". Both have arrows pointing to each other, representing the transitions that can happen between states.

While it wasn't perfect, I decided it was good enough, so I started coding the behaviour right away. My code looked something like this:

// Code simplified for explanation purposes
function onKeyPress() {
  if(button.visible) {
    restartTimer();
  } else {
    button.visible = true;
  }
}

function restartTimer() {
  if(timer.exists) {
    timer.delete();
  }
  
  timer = new Timer("3 seconds");
  if(timer.elapsed) {
  	button.visible = false;
  }
}

I wasn't really feeling the result. My beautiful button was popping in and out of the screen without much of a transition or animation which, I figured, wouldn't make the designers of my team to happy. So, to add some fanciness to the button, I opted for adding a 1s opacity transition between states. I ended with something like this:

// Code simplified for explanation purposes
function onKeyPress() {
  if(button.visible) {
    restartTimer();
  } else {
	// Wait for transition to complete.
    waitTransition("1 second", "opacity=1")
    button.visible = true;
  }
}

function restartTimer() {
  if(timer.exists) {
    timer.delete();
  }
  
  timer = new Timer("3 seconds");
  if(timer.elapsed) {
    waitTransition("1 second", "opacity=0")
  	button.visible = false;
  }
}

Yet, this introduced a new bug to my code. Did you spot it? If not, try going back to the code and see if you can find it.

It took me some time to find it to find the error, but here's a clue: What would happen if you pressed a key while a transition is happening? Since you pressed a key, the timer should restart and button's opacity should go back to 1.

How would you add this behaviour? For me, I first decided to add a new isFadingOut property to my button, so my code now looked like this:

// Code simplified for explanation purposes
function onKeyPress() {
  if(button.isFadingOut) {
    waitTransition("1 second", "opacity=1");
	button.visible = true;
  }
  else if(button.visible) {
    restartTimer();
  } else {
	// Wait for transition to complete.
    waitTransition("1 second", "opacity=1")
    button.visible = true;
  }
}

function restartTimer() {
  if(timer.exists) {
    timer.delete();
  }
  
  timer = new Timer("3 seconds");
  if(timer.elapsed) {
	// Wait for transition to complete.
	button.isFadingOut = true;
    waitTransition("1 second", "opacity=0")
	button.isFadingOut = false;
  	button.visible = false;
  }
}

This ended up creating a new list of bugs, most of them caused by a race condition. And, at that point, the code was getting out of hand! Now I had to deal with several timers at the same time. What if I had to add a new fadingIn state? How much would that mess up my code? So, after seeing this, I decided it was the perfect moment to change the way I approached the problem.

State Machines save the day.

You may have noticed that the opacity transition created a new "state" element. This can be added into our diagram like this:

A new circle has been added to the previous diagram. This new circle represent the "fadingIn" state that can happen when going from visible to invisible.

This diagram represents a State Machine, a set of determined states in which an application can exist and the relationships between them. State machine are a great tool to visualise all the states and transitions in our application. Every circle represents a state, while every arrow is a transition between states. Creating a diagram of one helps us see all the different inputs needed for a transition between states to happen. All in all, they are a great way to untangle almost any sort of boolean mess, like the one in our current application.

This is all great but, how do I use them?

One of the ways in which we can implement a State Machine is using enumerators. TypeScript has them, but they don't exist in JavaScript natively. However, we can simulate one using an object:

const buttonStates = {
  // You could also map these to a number instead of the same string,
  // but this is personal preference as it's easier to debug.
  fadingOut: "fadingOut",
  visible: "visible",
  invisible: "invisible"
};

We can then store the current state of our button in a property:

// start with a default state
button.state = buttonStates.visible;

And then add a new function in charge of transitioning between states:

function changeState(newState) {
  button.state = newState;
  
  if(newState === buttonStates.visible) {
    clearTransitions();
    waitTransition("1 second", "alpha=1");
	restartTimer();
  }
  
  if(newState === buttonStates.fadingOut) {
    waitTransition("1 second", "alpha=0")
  }
}

Finally, we need to adapt both our previous functions to take our new state into account:

function onKeyPress(){
  if(button.state === buttonStates.visible) {
    restartTimer();
  }
  
  if(button.state === buttonStates.invisible) {
    changeState(buttonStates.visible) 
  }
  
  if(button.state === buttonStates.fadingOut) {
  	changeState(buttonStates.visible)
  } 
}

function restartTimer() {
  if(timer.exists) {
    timer.delete();
  }
  
  timer = new Timer("3 seconds");
  if(timer.elapsed) {
	changeState(buttonStates.fadingOut)
  }
}

Not only is this easier to debug, but it also makes it simpler to add new States to our button. As an example, you could add a new fadingIn state by:

  1. Adding it to our enumerator
  2. Adding a new if statement both in changeState and restartTimer.

Once this is done, you may notice this logic won't easily clash with what we previously did. Every state has a different behaviour, and every individual behaviour is split into its own block.

When do I use them?

As I mentioned, State machines are a great tool for several use cases. They are implemented in day-to-day tools and can be seen in modern libraries such as xstate. However, they shouldn't always be used. There are some cases where a State Machine may make our logic even more complicated.

Here's a list of pros and cons I've found while working with them, which I hope will let you decide whether to use them or not:

Pros:

  • They make apps easier to debug, by separating each state into its own block
  • It's easy to add new states into your application
  • They make your code easier to read.

Cons:

  • They have a learning curve, people who are not familiar with them may find them confusing.
  • They require more code than a simple boolean, so they're probably not the best way to implement that on-off toggle you're working on.
  • Their logic gets complicated again when you have a lot of states.

Learn more about State Machines

Using enums and if/else statements is not the only way to create a state machine. The structure we did in this post is only one of the approaches you can follow to make one. If you'd like to learn more about them, here's a list of places where you can do so:

I love finding applications for design patterns such as this one in the real world and applying them into my own codebases. While I know several design patterns, I always have to dust off my knowledge a bit whenever I find a use for them as I rarely get to actually implement one. However, finding their applications and ending up with a better codebase as a result always brings me joy as a developer. And I hope this will be the case for you as well.

And, with this, I hope you learned something new. If you did, please take what you've learned, and make it better!

About the author

  • Hello! I'm Roberto, a Mexican Web engineer. I enjoy learning new things related to development to then share them with others 馃槃 You can easily find me on Bluesky: https://bsky.app/profile/robruizr.dev!

Great work ! It's always interesting to try implementing a pattern from scratch before switching to a fully fledged library like Xstate.

It got me thinking, I think you could take it one step further, while still avoiding any third-party dependency. Right now your changeState doesn't guarantee that you machine will be executed as described by your diagram.

For example nothing prevents you from calling changeState('fadeOut') from the state invisible which shouldn't be possible.

This could be solved by implementing the transition function from the mathematical defintion

Something like that :

First you'd add the transition to your state defintion


const buttonStates = {
  // You could also map these to a number instead of the same string,
  // but this is personal preference as it's easier to debug.
  fadingOut: {
    show: "visible",
    hide: "invisible"
  },
  visible: {
    reset: "visible",
    fade: "fadingOut"
 },
  invisible: "{
    show: "visible"
  }
};

Then the transition function could be defined like so:


 const transition = (state, event) => {
    return buttonStates[state][event]
}

Which would allow you to call transition(button.state, "fade")

Might be overkill for your use case, but thought it was worth mentioning :)

2

This was so informative! Love it!

2

Hey Rizel! Thank you! These sorts of comments inspire me a lot 馃槃

Loved it! I learned a lot here

2

That was a nice read Roberto Ruiz! I liked how you walked us through the problem and the solution.

2

Thank you!! Happy that you liked it :)

Love it - I think I just learned something new here 馃馃

2

Thank you!! I'm glad you did :)