Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 39 ยท State and Component Diagrams

State Machine Diagrams

Learn UML state machine diagrams: states, transitions, events, guards, actions, entry and exit behavior, with a runnable order example in Python.

Some objects behave differently depending on what has already happened to them. An order that has been shipped cannot be edited. A door that is locked ignores a push. A video player that is paused reacts to the Play button in a different way than one that is stopped. A state machine diagram describes exactly this: the states an object can be in, and the events that move it from one state to another.

State machine diagrams are the right tool when a single class has a lifecycle with rules. They are a poor tool for describing how many objects collaborate (use sequence diagrams for that). In this lesson you learn the notation, read a diagram aloud, and turn it into running code.

The parts of a state machine

A diagram contains a small set of elements.

  • State: a rounded rectangle. It is a period of time during which the object satisfies a condition, such as Paid or Locked.
  • Initial pseudostate: a filled black dot with an arrow to the first state. Every machine starts there.
  • Final state: a bullseye (a dot inside a circle). The lifecycle ends.
  • Transition: an arrow from a source state to a target state.
  • Event: the trigger that fires a transition, such as pay or cancel.
  • Guard: a boolean condition in square brackets. The transition only fires when the guard is true.
  • Action (effect): behavior executed during the transition, written after a slash.

A full transition label follows the pattern event [guard] / action. Every part is optional.

stateDiagram-v2
    [*] --> Created
    Created --> Paid : pay [amount OK] / sendReceipt
    Created --> Cancelled : cancel
    Paid --> Shipped : ship
    Paid --> Cancelled : cancel / refund
    Shipped --> Delivered : deliver
    Delivered --> [*]
    Cancelled --> [*]

An order lifecycle: reading the arrow Created --> Paid : pay [amount OK] / sendReceipt as "when pay arrives and the amount is OK, move to Paid and send a receipt".

Entry, exit and do behavior

Instead of repeating the same action on every incoming arrow, you can attach it to the state itself. Inside a state box you may list three kinds of internal behavior:

  • entry / action runs every time the state is entered, no matter which transition led there.
  • exit / action runs every time the state is left.
  • do / activity is an ongoing activity that runs as long as the object stays in the state and can be interrupted by an event.

Mermaid does not draw these compartments, so in a diagram you can add them as a note. In UML tools they appear under a line inside the state box. Use entry and exit actions for resource handling such as "entry / startTimer" and "exit / stopTimer": they keep the timer logic from scattering across five transitions.

If every arrow into a state carries the same action, it probably belongs in an entry action of that state.

Events, guards and the order of evaluation

An event is something that happens and is worth reacting to. UML distinguishes four kinds:

Event kind Example label Meaning
Signal / call pay(amount) Another object sends a message or calls an operation
Time after(30 min) A duration elapsed since entering the state
Absolute time at(midnight) A clock reached a point
Change when(stock = 0) A condition became true

A transition without an event is a completion transition: it fires automatically when the entry and do behavior of the state finished. A state that does validation work and then moves on is a typical user.

When the same event leaves a state through two arrows, the guards must be mutually exclusive, otherwise the model is ambiguous. For example Created --> Paid : pay [amount >= total] and Created --> Created : pay [amount < total] / showError split the event cleanly. A transition from a state back to itself is a self-transition; it runs exit and entry actions again. An internal transition (listed inside the state) reacts to the event without leaving, so no exit or entry happens.

What happens to events that do not match

If an event arrives and no transition leaves the current state for it, the event is simply ignored (UML calls it discarded). This is a feature: the diagram only lists what is allowed. A Shipped order silently ignores cancel unless you draw an arrow for it. When you review a diagram, look for missing arrows: "What should happen if the customer cancels a shipped order?" is exactly the kind of question state machines exist to raise.

Running the model

A state machine maps nicely onto a table of (state, event) -> new state. Press Run to see the order lifecycle execute, with guard and action.

Python Order state machine as a table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice how ship before payment is ignored, and so is every event once the order is cancelled. Nothing in the code says so explicitly: the missing table entries encode the rule.

Checking a diagram for completeness

A small program can find problems that humans overlook, such as states that can never be reached or that have no way out. Try it on a transition list.

Python Find unreachable and dead-end states

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the label pay [amount >= total] / sendReceipt mean?

    The pattern is event [guard] / action. The guard is checked when the event arrives.
  2. 2. An event arrives and no transition from the current state matches it. What happens?

    Unmatched events are discarded. This is how a state machine expresses what is not allowed in a state.
  3. 3. Where should an action that must run whenever a state is entered, by any path, be written?

    An entry action runs on every entry, so you write it once instead of repeating it on each arrow.
  4. 4. Which is a self-transition?

    A self-transition leaves and re-enters the same state. An internal transition would react without leaving.

Summary

  • A state machine diagram models the lifecycle of one object: states, events and transitions.
  • A transition label reads event [guard] / action; each part is optional.
  • Entry, exit and do behavior belong to the state, not to individual arrows.
  • Events that do not match any outgoing transition are ignored, so missing arrows are rules.
  • A (state, event) table is a direct way to implement and check a diagram.

Next: Composite States, Regions and History