Deterministic vs. non-deterministic state machine
When using a state machine in you design you can use either deterministic or non-deterministic state machine. Following a work discussion I had regarding this issue few conclusions follows.
Non deterministic state machine
In this machine design, each state is “allowed” to have internal logic and be stateful in order to determine the next state to go to following an event. So the main interface will be:
State onEvent(Event e)
Deterministic state machine
In this style of machine, there’s a finite, pre-defined list of transitions, that fully determine the next state to go to following an event. So, each state can handle events by running code, but the next state to go to is predefined and known by explicit declaration. Hence, the interface will look like this:
Void onEvent(Event e)
What design is better ? I think they both good and each one has pros and cons.
I think the main differentiator between the two designs is that in a deterministic state machine , for a given series of events, you know what code runs without looking at the code, achieving this only by checking the transition map. This is not the case for non-deterministic machine because states’ internal logic determine the next state so you must read code to know what’s the next state that the machine will transit to.
State’s internal logic
The above main difference outcome is that in deterministic machines, you must use machine states and events to implement one state’s logic while in non-deterministic one, a state’s internal logic can be kept internal and the machine states and event can be fewer and in higher resemblance to the real physical world events.