Found it surprisingly difficult to code well, regardless on the language, esp. when there're many states.
Found it surprisingly difficult to code well, regardless on the language, esp. when there're many states.
In one of my prev workplaces we worked on state machines. Few good takeaways was to design state transition functions in a large array laid out with all possible hooks in order. And document the hell out ofit. Another approach was to generate boiler plate out of fsm given its grammar.
I wish someone would invent an approach suitable for generic FSMs, not just for async IO. External code generators work when you have grammar or protocol state UML, but aren’t without their problems.
http://docs.dapt.in/state_tracking/
Would love feedback.
Here’s an example of FSM with relatively complex state, 1000-lines gc_execute_line function, it’s for CNC: https://github.com/grbl/grbl/blob/master/grbl/gcode.c
That’s not my code, but I’m not sure I would be able to do much better than that.
switch(letter) {
case 'G':
switch(int_value) {
case 4:
switch(int_value) { // int_value hasn't changed
case 10: ... // so how do we get to this case?
That second switch on int_value is at line 151. Have I missed something in the code where int_value is changing?However, above that “case 4:” there’re another cases, “case 10: case 28: case 30: case 92: ” without break at the end of the code. Unlike some other languages, in C and C++ this means execution continues to the next case. The behavior is called "switch statement fallthrough".
That source code has the comment saying “No break. Continues to next line.”