Search code examples
playbackstate-machine

why do we need to design a state machine to implement a playback app?


can't we just write some play() stop() pause() function instead?
what's the advantage of using a state machine to do this?


Solution

  • The main advantage in your case is that each state determines what actions are valid and how the state machine reacts on them.

    In a very simple model your state machine would have the states

    • Playing
    • Pausing
    • Not Playing

    Each of these states defines which actions are valid. It makes no sense to allow a call to Play() in state Playing. It also makes no sense to allow Stop() in state Not Playing. The state machine helps you figuring out what actions are valid in which state.

    By the way: Every program is kind of a state machine, but not every program is modeled after one. By creating the model your code automatically becomes more structured and readability increases.