by monocasa · 4y ago · 0 comments
The most common way to abstractly describe state machines is the directed graph, but (like nearly all graph problems) it's often just as illuminating if not more to decompose the graph into a matrix as well. So rows are states, columns are events, and the intersections are transitions. Being able to run down a column and see what happens in each of the states when a certain event is processed has made a lot of bugs much more obvious for me.
Now when documentating a state machine enough to actually draw out the graph, I always include a matrix representation as well for that reason.
The best result was the time we spent an hour at the whiteboard, then the team split up and we each re–wrote part of the code (there was message–passing between components involved, so we just each took one component; I had cleverly used the events between components in the state machine in addition to external events). We all committed by the end of the day, and the next day QA said it was perfect. (Eventually I think some automated tests got written, but whatever.) Compare that to the prior months where QA would find some weird problem, someone would debug it, write a patch, and declare it fixed without realizing that they had broken some other edge case. There were never any bugs found in that thing ever again.
Incidence matrices[1] might be an effective way to represent graphs, but the sparse nature of state machines combined with large numbers of input events and states end up making it hard to represent non-trivial state machines.
Also, state machines are often organized into sub-state machines, which are not adequately represented with incidence matrices.
It doesn't sound too hard but I'm sure there are wrinkles.
Foreach node
Foreach node.transition
Matrix(node, transition.event) = transition.destination
And the other way: Foreach node
Foreach event
Destination = matrix(node, event)
Graph(node).add(event, destination)