Is a finite state machine an appropriate solution for this situation?

Posted by user1936 on Programmers See other posts from Programmers or by user1936
Published on 2013-07-01T18:00:48Z Indexed on 2013/07/01 23:14 UTC
Read the original article Hit count: 244

Filed under:

I was writing some test code as an example where I had a washing machine class. It has a door state that should be open or closed, and also a running state, either on or off. I want to prevent the running state from changing from 'off' to 'on' when the door is 'open', and also prevent the door from being set to 'open' while the machine is 'on'.

I have this functionality rigged up with a bunch of if statements. It feels inelegant and it could quickly turn into spaghetti code if I want to add another state that puts additional conditions on the changes of other states. I wonder, is a finite state machine a solution for this situation? Would it simplify adding states and defining valid transitions?

© Programmers or respective owner

Related posts about finite-state-machine