3 ms·
Like the GoF design patterns, knowing about state machines is important, but whether or not you should use them in their "pure" form depends on the problem at h
by GuB-42 4y ago
Like the GoF design patterns, knowing about state machines is important, but whether or not you should use them in their "pure" form depends on the problem at hand.
State machine make for some the least readable code I have written and an ad-hoc solution could have been more appropriate. The difficulties I have with state machines is, as usual, side effects. That is, implementing the state transition logic is usually straightforward, but more often than not, there is something you want to do between these states, typically I/O. In a pure framework, it manifests as a hidden, extra state, for witch the "right" thing to do is to make it explicit, and you may end up with a monster state and transitions all over the place. I have written a few of these monsters, and while I think it is partly the result of inherent complexity, I must say it is not the code I am the most proud of.
In other situations, state machines were a perfect match, but like everything else, just because the problem can be modeled with a state machine doesn't mean it should.
- Cthulhu_ 4y agoOne great example of state machines being used in the wild is in video games, e.g. playable and non-playable characters; for a simple 2D game, a player could be in a state "moving left", "right", "jumping", "falling", etc. Although it might quickly become a case where two states can be active (jumping & shooting), or there's different states for different things (e.g. animation state separate from movement state).
- giraffe_lady 4y agoI do some work in ocaml where state machines are popular I think because of how cleanly they map onto the language constructs. One common approach is the elm-ish move of having the machine fn return a pair of (new state, action). Then you have an intermediate fn run the side effects, but you can implement that somewhere else and mostly pretend it's not there. React reducers are kind of like this too. When doing this though like you said you always either find there are more states than you initially thought, or you end up having pseudostates only for their effects. I pretty much only reach for state machines when I know the inputs will never change and I'll never have to modify the implementation. Even in a language almost perfectly suited for them they are hard to understand once they're doing all the edge cases and side effects and edge cases of the side effects and error handling etc etc.