Go Down

Topic: Finite State Machine Using Switch Statement. (Read 9 times) previous topic - next topic



the more i search and trying to understand what is Finite State Machine, the more i understand and the more i realized how much i need to know when it come to programming . however i cant help but to see the similarity between Finite State Machine with the step sequence that i use to used when programming PLC


if(state=="try"){ //do actions here }
if(state=="it"){ //  ....}

basically it be done like that.



Switch and functions will certainly help you to build a state machine. Sometimes your tests and state transitions are simple enough that they can go directly in the switch. I like to keep loop small enough (like any other function) that it can be read without scrolling though, so generally, I'll call a function that handles each state from the (then) simple switch. Here's an example I posted a while back that illustrates both:


Sometimes, the system is so simple that a state machine is hardly worth it, but it still makes a nice framework. Also, if functionality is added later, you don't find yourself cursing that you should have used the concept from the start. This one shows this:


Here's another example, pretty pure, one function to handle each state:


Repeating Jack's advice, if you use this switch and function call model, the state machine practically writes itself - as long as you have specified your states and possible transitions up front.

Go Up