Skip to content

Commit 3566c54

Browse files
Add "what is a state machine" blog post (#216)
* Add "what is a state machine" blog post * Tweak intro * Clarify first sentence * Tweaks * Remove section * Tweaking * What is a state machine updates (#221) * Work on blog post * Tweak blog post and add links and more info about Stately * Update blog/2023-10-02-what-is-a-state-machine/index.mdx Co-authored-by: David Khourshid <[email protected]> * Move stories markdown into admonition (and render properly) --------- Co-authored-by: David Khourshid <[email protected]> --------- Co-authored-by: Laura Kalbag <[email protected]>
1 parent edb2376 commit 3566c54

File tree

10 files changed

+223
-0
lines changed

10 files changed

+223
-0
lines changed
Lines changed: 221 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,221 @@
1+
---
2+
title: What is a state machine?
3+
description: Learn what a state machine is, and how it can help you model and understand complex systems visually.
4+
tags: [state machine, statechart]
5+
authors: [david]
6+
slug: 2023-10-05-what-is-a-state-machine
7+
image: /blog/2023-10-05-what-is-a-state-machine.png
8+
date: 2023-10-05
9+
---
10+
11+
You might have heard of “state machine” or “finite-state machine” before. [If you look up _state machine_ on Wikipedia](https://en.wikipedia.org/wiki/Finite-state_machine), you’ll read that a state machine is described as a “mathematical model of computation,” followed by a bunch of symbols and computer science jargon that doesn’t immediately seem to apply to your team’s work.
12+
13+
However, state machines are _really useful_ for describing almost any kind of logic, feature, user story, sequence, process, workflow, specification, and more. <!--truncate-->They can greatly improve how your team collaborates on processes, flows, features, and any other kinds of application logic, and they’re much simpler to understand than you may think.
14+
15+
If you’ve worked with flowcharts or diagrammed a process on a whiteboard with boxes and arrows, you may already know how state machines work!
16+
17+
# What is a state machine?
18+
19+
A state machine is a way of modeling how something works, using states and transitions to show how something changes over time in response to events.
20+
21+
![Two states of locked and unlocked. On the unlocked state you can transition to un-locked on a coin event or transition to locked on a push event. On the locked state you can transition to un-locked with a coin event or transition to locked with a push event.](turnstile-state-machine.svg)
22+
23+
Specifically, it formally models how a system transitions from one state to another based on specific events (e.g., triggers, signals, changes, etc.). Think of it as a useful tool for visualizing and designing the flow of user experiences, product features, or any process you’re working on.
24+
25+
Visually, state machine diagrams are similar to flowcharts. Both use shapes to represent states (e.g., steps in a flow) and arrows to indicate transitions between those states. The main difference is that state machines are more precise, formal, and powerful than flowcharts. They’re also more flexible since you can use them to model any kind of logic, not just processes.
26+
27+
<p>
28+
<ThemedImage
29+
alt="A booking state machine with an initial idle state. From idle you can transition to car booking, flight booking, and hotel booking states."
30+
sources={{
31+
light:
32+
'https://prodstack-ogimagebuckete7b3c4ce-fcz4tpdpagli.s3.amazonaws.com/studio-ec345257-35c4-4fcc-bfbc-9a9255bc8d13-light.png',
33+
dark: 'https://prodstack-ogimagebuckete7b3c4ce-fcz4tpdpagli.s3.amazonaws.com/studio-ec345257-35c4-4fcc-bfbc-9a9255bc8d13-dark.png',
34+
}}
35+
/>
36+
</p>
37+
38+
State machines are a concept deeply rooted in computer science; however, they have broad applications that extend to various business domains and design disciplines. From developing intuitive software interfaces to designing effective business processes, state machines provide a structured way to model and understand complex systems. Whether you’re a product owner, project manager, designer, developer, QA tester, business analyst, or any other role, understanding state machines can significantly improve your ability to design, manage, and refine features, processes, and products.
39+
40+
In short, a state machine lets us clearly understand how something reacts when an event occurs.
41+
42+
## The parts of a state machine
43+
44+
Visually, state machines are just boxes and arrows. The building blocks of a state machine – **states, events,** and **transitions,** are quite straightforward (no pun intended), but together, they form a powerful tool for modeling and understanding systems.
45+
46+
### States
47+
48+
A [state](/docs/states/intro) represents a particular situation, mode, or status that something can be in. For instance, an e-commerce site’s order can be in the _Pending_, _Shipped_, _Delivered_, or _Returned_ states. Each of these is a finite state, contributing to the entire lifecycle of an order.
49+
50+
<p>
51+
<ThemedImage
52+
alt="Pending and shipped states."
53+
sources={{
54+
light: '/blog/2023-10-02-what-is-a-state-machine/order-states-light.png',
55+
dark: '/blog/2023-10-02-what-is-a-state-machine/order-states-dark.png',
56+
}}
57+
/>
58+
</p>
59+
60+
Finite states are **deterministic**, meaning that something can only be in exactly one finite state at a time. An order cannot be in both the _Pending_ and _Delivered_ states at the same time, just like you can’t be in both the _Asleep_ and _Awake_ states simultaneously.
61+
62+
State machines always start at an **[initial state](/docs/states/initial-states)** and may end up in a **[final state](/docs/states/final-states)**, indicating that the state machine is “done” and can no longer transition to any other state.
63+
64+
### Events
65+
66+
Events are occurrences; they’re a record that something happened. Using the previous example, an event like _item shipped_ might transition an order’s state from _Pending_ to _Shipped_.
67+
68+
<p>
69+
<ThemedImage
70+
alt="There is an initial Pending state. The machine transitions from Pending to the Shipped state with the item shipped event."
71+
sources={{
72+
light: '/blog/2023-10-02-what-is-a-state-machine/order-event-light.png',
73+
dark: '/blog/2023-10-02-what-is-a-state-machine/order-event-dark.png',
74+
}}
75+
/>
76+
</p>
77+
78+
### Transitions
79+
80+
A state [transition](/docs/transitions-and-events/intro) describes how a system “moves” from one state to another. These are the arrows between the states, labeled by the event that causes the transition to occur.
81+
82+
In state machines, transitions always happen immediately. For example, an order can be _Pending_ for some time (almost frustratingly so), but when the _item shipped_ event occurs, it immediately transitions to the _Shipped_ state.
83+
84+
<p>
85+
<ThemedImage
86+
alt="State machine for an order: the states are pending, shipped, delivered, and returned."
87+
sources={{
88+
light:
89+
'/blog/2023-10-02-what-is-a-state-machine/order-transitions-light.png',
90+
dark: '/blog/2023-10-02-what-is-a-state-machine/order-transitions-dark.png',
91+
}}
92+
/>
93+
</p>
94+
95+
[View this state machine in Stately](https://stately.ai/registry/editor/092bf401-2d65-48ae-969c-99b4a7eeb87f?machineId=942c00ac-7922-4a5a-bf92-d2438847c62f&mode=design).
96+
97+
## A state machine example
98+
99+
Let’s say you wanted to create a flow for a travel booking app. This flow represents the logic of a user booking a flight, hotel, and rental car, and you can apply this logic to the frontend code (as a multi-step flow) and backend code (as a workflow that communicates with APIs to book everything). Let’s model this travel booking flow as a state machine.
100+
101+
First, think of all of the **states** of this flow. Each state represents something that is happening, such as the flight or hotel being booked:
102+
103+
- Booking flight
104+
- Booking hotel
105+
- Booking car
106+
- Confirmation
107+
- Error
108+
109+
Tip: make sure to handle errors! In the real world, things don’t always go according to plan.
110+
111+
Then, think of all the **events** that can happen in the flow. There are the “happy-path” events:
112+
113+
- Flight booked
114+
- Hotel booked
115+
- Car booked
116+
117+
But other events can happen:
118+
119+
- Flight booking failed
120+
- Hotel booking failed
121+
- Car booking failed
122+
- Timeout
123+
124+
You can then combine these states and events to create a complete **state machine diagram** that represents all the possible user flows through the app:
125+
126+
<EmbedMachine
127+
name="booking machine"
128+
embedURL="https://stately.ai/registry/editor/embed/9fa24cc0-3026-41be-bb22-9afc3980fefc?machineId=5e614700-7fc3-4d22-adce-4dd6cf4f6de0&mode=Design"
129+
/>
130+
131+
The state machine above uses parent and child states, a feature of [statecharts](/docs/state-machines-and-statecharts#what-is-a-statechart), to reduce complexity.
132+
133+
These state machines serve as a **source of truth** for your app logic since you can use them for:
134+
135+
- **Documentation** that outlines the features and use cases represented in the flow
136+
- **Code** you can generate from the state machine
137+
- **Diagrams** as visual documentation
138+
- **Tests** you can also generate for various flows
139+
140+
## Benefits of using state machines
141+
142+
Understanding and managing anything that can happen in your applications is crucial for [efficient collaboration and innovation](/blog/using-teams-in-stately-studio) – you want to ensure that your team can understand and iterate on app logic and features quickly, no matter how complex they get. State machines are a powerful visual approach for accomplishing that, and they’re much more than just a diagramming tool.
143+
144+
There are many key advantages of using state machines:
145+
146+
### Visualized documentation
147+
148+
With state machine diagrams, you can visually represent the states of a process, making it easier to grasp and communicate complex logic. These diagrams bridge the communication gap between technical and non-technical team members. They also provide a clear way to document and share app logic, which you could use for onboarding new team members. After all, following boxes and arrows (just like a flowchart) is much easier than parsing code, especially for someone unfamiliar with the codebase.
149+
150+
![A mermaid diagram of our order state machine.](mermaid-diagram.svg)
151+
152+
_Our [export to Mermaid feature](/docs/export-as-code#export-formats) enables you to embed your state machines in GitHub and GitLab pull requests and comments._
153+
154+
### Consistent, robust application logic
155+
156+
By mapping out all states and transitions, state machines ensure you account for every possible scenario. This minimizes unexpected behaviors (such as undesired states/transitions) and system inconsistencies because it is **mathematically impossible** for a state machine to take a transition that does not exist. You can quickly identify a transition to a state that should not go to that state. This is especially useful for complex apps, where it’s easy to miss edge cases or unexpected scenarios.
157+
158+
### Modularity and scalability
159+
160+
State machines allow for isolating logic, meaning you can make changes or additions to a specific segment without overhauling the entire system. Regardless of framework, programming language, or implementation, the core abstractions remain the same: states, events, and transitions. If you need to add, change, or remove a feature, the process is to add, change, or remove states and transitions.
161+
162+
### Test path generation
163+
164+
State machines clearly define all possible states, events, and transitions, allowing testers to simulate specific events and verify if transitions to specific states occur as expected. Since state machines are directed graphs, they act like a “map” for your app logic. This map enables the automatic generation of many different “paths” through the state machine. Each path represents a potential use case, even those that may initially go unnoticed, such as edge cases. Exhaustive test path generation is also possible so that you can test every possible path through the state machine.
165+
166+
:::info
167+
168+
_Our [export to Stories feature](/docs/export-as-code#export-formats) enables you to generate the happy paths (stories) for your app:_
169+
170+
### Stories for `orderMachine`
171+
172+
#### orderMachine.Pending
173+
174+
1. _Start_
175+
**State** `orderMachine.Pending`
176+
177+
#### orderMachine.Shipped
178+
179+
1. _Start_
180+
**State** `orderMachine.Pending`
181+
182+
2. **Event** `item shipped`
183+
**State** `orderMachine.Shipped`
184+
185+
#### orderMachine.Delivered
186+
187+
1. _Start_
188+
**State** `orderMachine.Pending`
189+
190+
2. **Event** `item shipped`
191+
**State** `orderMachine.Shipped`
192+
193+
3. **Event** `item delivered`
194+
**State** `orderMachine.Delivered`
195+
196+
#### orderMachine.Returned
197+
198+
1. _Start_
199+
**State** `orderMachine.Pending`
200+
201+
2. **Event** `item shipped`
202+
**State** `orderMachine.Shipped`
203+
204+
3. **Event** `item delivered`
205+
**State** `orderMachine.Delivered`
206+
207+
4. **Event** `item returned`
208+
**State** `orderMachine.Returned`
209+
210+
:::
211+
212+
## Transition to state machines
213+
214+
We love state machines at [Stately](/) because we know how valuable they can be to development teams. State machines provide a visually clear way to understand, design, and manage flows and logic at any level of complexity. Integrating the principles of state machines can lead to more predictable outcomes, clearer communication, and enhanced efficiency for the entire team, from project managers to designers and developers. You can use them as a precise way of diagramming and documenting app logic and even use them in your codebase to power that same logic.
215+
216+
There are many ways to get started with state machines:
217+
218+
- [Watch our video intro to Stately](https://www.youtube.com/watch?v=EzYIerEutgk).
219+
- [Learn about generating state machines from text descriptions](https://www.youtube.com/watch?v=wjZE39wCZXo) with our AI feature.
220+
- [Read more about using XState](/docs/xstate), our open-source library for state machines anywhere JavaScript is supported.
221+
- Jump into creating your own machine in [our drag-and-drop editor at state.new](https://state.new).

0 commit comments

Comments
 (0)