Use Finite-state Machine to manage state
Introduction
Main Elements:
- States: must be limited
- Events
- Transitions: when
event 1
fromstate A
tostate B
- Actions: when
state|event|transition
changed then actaction
from https://en.wikipedia.org/wiki/Finite-state_machine, Fig. 3
Why We Need this
To make sure complex things never gone off the rails
- Add constraints on states, throw errors to avoid bad things
- Help to sort out reaction when state changed
- Code is documentation
Different with Flux-like State Managements
Flux-like State Managements(Redux/MobX/NgRx) is a way to manage states by utilizing unidirectional data flows, it is often to using this kind of state management with functional programming.
Redux lifecycle, from https://dev.to/radiumsharma06/abc-of-redux-5461, Fig. 1
It is easier to use FSM to manage state with object-oriented programming, but that did’t mean you can’t choose flux-like state management as your state management in object-oriented programming.
Actually, I kind of perfer using flux-like state management in morden frontend framework(React/Vue/Angular), because of these framework encourage you to use functional programming/unidirectional data flows.
Most of backend frameworks(Spring/Rails/Django/.NET) is develop by object-oriented programming languages, so using FSM to manage object state is totally reasonable.
Libaries
For Ruby
For JavaScript or TypeScript
For C#
References
- https://en.wikipedia.org/wiki/Finite-state_machine
- https://github.com/aasm/aasm
- https://github.com/davidkpiano/xstate
- https://github.com/dotnet-state-machine/stateless
- https://stackoverflow.com/a/54521035
- https://medium.com/pm的生產力工具箱/如何有邏輯的釐清事物的狀態-f9fb59b15054
- https://facebook.github.io/flux/docs/in-depth-overview/
- https://dev.to/radiumsharma06/abc-of-redux-5461
Use Finite-state Machine to manage state
https://blog.yang-hong-xin.com/use-finite-state-machine-to-manage-state/