Mark As Completed Discussion

Introduction

You may have heard of a concept of state machines or more formally finite state machines. But what are they?

State machines serve as a mechanism to transition something from one state to the other. They have three key components:

  • States are the possible configurations something can be in. The current state can influence what is currently happening, what values certain variables may have, and what other states are accessible from it.
  • Transitions are connections between states. They allow the program to move from one state to another connected state under certain conditions.
  • Events are aforementioned "certain conditions" - they are changes in a program or data it's accessing that trigger a transition from one state to the next.

All this might be a bit abstract, so let's use an everyday example to illustrate how state machines may be used to program a home appliance, like the AC. Let's assume it's set to automatic temperature adjustment.

Introduction

We can see in this picture the white squares are the possible states of our AC (Off, Heating, Cooling, or Standby). The states are pretty self-explanatory, with the difference between Off and Standby being that in Standby the AC is on and monitoring current temperature to see if it should start heating or cooling.

We have our red arrows that are the possible transitions and green letters for events that trigger each transition. When the AC is Off it can transition to any of the other states depending on how the current room temperature as read by the thermometer compares to the temperature we've set on the AC. If it's colder, it's going to start Heating, if it's hotter, it's going to start Cooling, and if the temperatures are exactly the same it will go into Standby. We can also return to Off state from any of the states when the Off switch is pressed. If you follow this logic, you'll see how the AC keeps the room temperature around the set value consistently.

Events and transitions are fundamentally linked, but it's important to separate them out. One event can trigger multiple transitions (such as Press Off in our example) depending on the state we're currently in or trigger different transitions (such as Press On) depending on values of current variables. In a larger system, an event can be a complex trigger, setting off many procedures and transitions, and the state machine would be just one of its subscribers, waiting for their signal to determine what to do.