State machines

State machines provide a way to break complex behavior into well-defined states and transitions.

State machine

A state machine is a model for describing system behavior over time.

In a state machine:

  • a task is broken down into a series of states
  • the system moves through these states along defined transitions
  • the system transitions from one state to another based on inputs or other triggers

Examples of systems controlled by state machines include:

  • elevators
  • traffic lights
  • vending machines

Each of these systems:

  • can only be in one state at any given time
  • can perform different actions depending on inputs

States, Transitions, and Events

A state:

  • describes the status of a system while it is waiting for a transition
  • is one of a finite number of possible conditions
  • for this reason, state machines are called finite state machines (FSMs)

A transition:

  • is the action of moving from one state to another
  • transitions are usually triggered by events

An event:

  • is something that occurs, e.g., a button press or a timer expiring
  • the same event might trigger a different transition depending on the current state of the state machine
  • e.g., pressing the “5” button will make an elevator go down if it’s on the tenth floor, or go up if it is on the first floor

Designing a state machine entails:

  • determining all possible states
  • planning the transitions between states
  • identifying the events that trigger those transitions

Avant Quotes from Steve Jobs in Exile Après Notes on the Internet

Kemar Joint