Hacker News new | ask | show | jobs
by carlbarrdahl 1943 days ago
How come there isn't better re-usability in state machines?

It seems it would be powerful if they were treated as re-usable lego bricks of state and logic.

Apps could then pull these in, connect the wires to any potential backend, and style the interactive components.

2 comments

What makes them reusable is dependent on how you implement them.

A state machine that is the simple relation:

(state, event) => [state', actions]

has a very reusable interface, as long as it doesn't execute the actions (effects, commands, etc.) itself. It's just a pure function that can be used anywhere to get the next state and the actions to execute as a result of receiving an event.

Then you can do exactly what you're describing: connect the wires, style the components according to state, etc.

Thank you David. Your xstate repo on github brought my attention to state machines and state-charts. Which I guess is why I'm interacting with this thread right now.

I often wonder what would happen if we could find ways to build complex applications by creating re-usable blocks using state machines (state, logic), json-schemas (structure, data-model), and React* (presentation).

All of these are serializable documents. Imagine being able to search a collective collaboration of components and schemas and piece it together. Could probably be graphical interface like Figma.

There are certainly other pieces that could be also used (graphql to describe data-fetching, markdown (mdx) for content).

*or similar

I'm currently building this! More info to come soon.
You probably are already familiar, but if not, this is exactly the entire concept behind Elm (in fact that signature is exactly the update function at the heart of the Elm architecture). And indeed the Elm community has a lot of ideas on how to split that basic idea to make it reusable.
At a previous company we used statemachines to debounce signals, implement protocols, and sequence robot moves. While they were designed so that the actions executed on state entry were pluggable (i.e. all action were executed by calling through a C# interfaxe), in practice we did not use it. Instead were abstracted at a slightly higher level: components that wrapped statemachines with some extra logic and nice APIs. The inputs for the statemachines were also pluggable, so different sources of digital inputs or motor control could be used.