Use Finite-state Machine to manage state

Introduction

Main Elements:

  • States: must be limited
  • Events
  • Transitions: when event 1 from state A to state B
  • Actions: when state|event|transition changed then act action

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

作者

楊竑昕

發表於

2021-07-03

更新於

2023-04-03

許可協議

評論