News for hackers. Stuff that matters.
Re:Facts about State Machines by alain94040 on Friday September 30, 2022 @06:45PM (#33041703)
The primer is simple: if you notice that your code is using too many if statements, especially nested ones, and you are starting to wonder if you are covering all alternatives and cases, then using the rigor of a state machine may help.

You know, that kind of code:

  if(start) {
    if(!running) ...
  }
  
  if(stopped & !jumping) {
  } else if(running) ...
Stop and write a proper case statement (aka a state machine). You may discover that combinations of booleans (in my example, stopped & !jumping) deserve to be their own state. The insight is that the resulting code should be one clean case statement, with no nested ifs allowed. Then you know you cover all the states/cases.
Re:Facts about State Machines by a1445c8b on Friday September 30, 2022 @07:32PM (#33042062)
“If” conditions and state machines are not mutually exclusive. You can implement a proper State machine with “If” conditions.

That switch-case alternative you’re suggesting? That’s just another manifestation of the same concept behind “If” conditions. So, really, with case statements, you’re still implementing nested conditions, just in mixed ways (a mix of case statements and “If” conditions)

The distinguishing characteristic between state machine and bad logic is that the top level conditions are the states, rather than the inputs.

EDIT: for clarity.

Re:Facts about State Machines by lfowles on Friday September 30, 2022 @08:30PM (#33042501)
Programming is state machines all the way down, it's just the convenience of expression that makes a difference.
Re:Facts about State Machines by a1445c8b on Saturday October 01, 2022 @05:26PM (#33050266)
More than just convenience of expression, it guards against "impossible states." This article[1] does a good job of explaining it.

[1] https://dev.to/davidkpiano/you-don-t-need-a-library-for-stat...