Hey @xilnocas, thanks for the mention! I’m excited to see the broader conversation around state machines and statecharts.
I’m somewhat new to Elm (made a few experiments before and begged for CSS variables to be included in Elm’s virtual DOM…cough), but I’d like to answer the questions posed in a general context.
- How should we approach explaining state machines to beginners?
I don’t think this question is a mistake. I think it’s an extremely valuable endeavor, but instead of approaching it as “learn about deterministic finite automata” and other CS-related concepts, it’s better to approach it from “instead of developing an app bottom-up, think about the overall logic and plan it out, top-down”.
Elm’s code might look succinct, but there’s nothing easier than pencil and paper - and this is a great, intuitive way to learn what state machines are. Even people who have absolutely no experience in coding will be able to draw circles, arrows, and labels that explain “If we’re here, and we do this, then we go here”. In fact, this is how designers intuitively think - user flows are state machines!
- Do we need the word “state machine” at all?
Sure. There’s lots of great references and learning material available by putting a name (“state machine” or “automata”) to an abstract but intuitive pattern of modeling application logic.
- Are there any potentially big risks I’m not seeing?
Oh yes - state explosion, representing simultaneous states in a (supposedly) deterministic way, dealing with side-effects and temporal states, knowing how to organize multiple states, state history, etc. etc.
However, those are all solved with the notion of statecharts, which are an extension of (and fully compatible with) finite state machines (they’re essentially hierarchical finite state machines).
Note: statecharts are not easy to implement (xstate is my in-progress implementation) but the idea is the same: you have a pure transition function which takes the current state, action, and returns the next state. If you squint, Elm’s architecture naturally models this pattern (except not in as structured a way as a formal statechart definition).
We need to approach and teach state machines and statecharts from the perspective of designing complex user interfaces and applications, instead of from a heavily theoretical computer science approach. I fully intend to experiment on bringing the statechart formalism to Elm and seeing how Elm apps can be modeled with such an approach.
Also important to note that it’s not just a different way to code. It’s a way to have your application logic fully declarative so that you can easily visualize and automatically generate full integration tests for your entire app, and also make it easy to refactor, since a “feature” is just a node in a directed graph.