Ask HN:
"Can a state machine be stateless?"
(Replying to PARENT post)
Example: Valid states have values of 1, 2 and 5. For some reason the current state has a value of 17. It's not a valid state but it is a state.
As such, there needs to be provision for it, generating an error of some kind. As in:
....
switch (state){
case ALPHA:
printf("State is alpha\n");
break;
case BETA:
printf("State is beta\n");
break;
case OMEGA:
printf("State is omega\n");
break;
default:
printf("ERROR! State value %d is INVALID\n", state);
error(state);
break;
}
....
(Replying to PARENT post)
Advantage of that approach is that it makes it easier to test the state machine (if you want a test that checks what it does on receiving input I while in state S you donβt have to somehow get it into state S, but just call it with those inputs) and that it means you can (easily) write the function so that it is reentrant, and thus allows you to instantiate the state machine multiple times (if only for running tests in parallel)
For some state machines, it may not even be possible to get them in state S enough times to test them with all inputs you want to test them with, if you βhideβ the current state inside the transition function.
(Replying to PARENT post)
Edit: To answer your two questions:
1) No, it's not stateless.
2) Depending on the implementation of the function, yes, it may be a valid state machine. Or, it may not be. Depends on the implementation of the state machine within the function.
(Replying to PARENT post)
(Replying to PARENT post)
The difference is that you are separating the input & the current state from the state transitions. The state transitions can be encoded as a matrix or nested case/switch statements - which do not have state.
(Replying to PARENT post)
Note that to be a _true_ Finite State Machine, the reducer function would need to be written to first check what state value it's currently in, _then_ decide if the input is relevant. Most Redux reducers are not actually written that way - they just update the state value based on the action, regardless of what the existing state was.
References:
- https://redux.js.org/style-guide/#treat-reducers-as-state-ma...
- https://dev.to/davidkpiano/redux-is-half-of-a-pattern-1-2-1h...
(source: I maintain Redux, and that Redux style guide entry and the additional blog post were written by David Khourshid, who is an expert on state machines.)