Search code examples
javascriptstate-machine

What is a Finite State Machine and What is it Used For?


Recently, I've begun doing some research into Finite State Machines in JavaScript and I even found a library that makes them easier to implement. While I think I've grasped the idea that a state machine is used for tracking and changing the "state" of an object (e.g., 'ready', 'complete', 'inactive', etc.,), I don't think I fully understand the practical implications of them. Could someone please help by clarifying the following:

  • What exactly is a finite state machine [or is it just called a state machine? I've heard it referred to both ways]?
  • What are some practical uses for finite state machines (in JavaScript)?
  • When would I not want to use an finite state machine?
  • What books, articles, tutorials, etc., offer a more in-depth look at finite state machines (in JavaScript)?

Solution

  • A Finite State Machine is an abstract concept. As such, the concept of state machine is orthogonal to any particular language. If you look at wikipedia, it says "is a mathematical model of computation used to design both computer programs and sequential logic circuits".

    This means that FSM usually used as mathematical concept that is used by computer scientists to address questions with the discipline, like "can xyz be computed at all?"

    Based on your question, and your link, I think you mean to ask about State Diagram (or Statechart) which is different. When you create a state diagram, you are dividing your program in a series of states, and the events that can occur in those states. For example, your program might be in the "EditingForm" state, receive the event "doSave", and then go into the "Saving" state, receive the event 'Save Complete", and go back into the "Viewing" state.

    This abstraction is incredibly useful because it allows the programmer to conceptually organize what things should happen when, which when implemented correctly, leads to cleaner and more organized code. This in turn leads to fewer bugs. A state diagram, depending on the implementation, can prevent unintended effects by only handling the events defined for a state -- For example, the "Viewing" probably does not have a 'save' event defined, thus if the program is in the "Viewing" state any Save is meaningless, as that should only happen in the "Editing" state.

    If you look at the overview of the framework to which you link, you will notice there are a bunch of handlers you can use to hook into entering states, leaving states, actions happening, etc. This allows you to actually do things that correspond to the state/action. For example, on entering the "Editing" state you might present the form to the user and enable the save button. On entering the "Saving" state you might disable the button and fire a request to save. On receiving the "SaveComplete" event you might transition to the "Viewing" state, remove the form, and show something else.