title: C++ code for state machine
body: <p>This was an interview question to be coded in C++: </p>
  
  <blockquote>
    <p>Write code for a vending machine: Start with a simple one where it just vends one type of item. So two state variables: money and inventory, would do. </p>
  </blockquote>
  
  <p>My answer:</p>
  
  <p>I would use a state machine which has about 3-4 states. Use an enum variable to indicate the state and use a switch case statement, where each case has the operations to be done corresponding to each state and stay in a loop to move from one state to another. </p>
  
  <p>The next question:</p>
  
  <blockquote>
    <p>But using a switch case statement does not "scale well" for more states being added and modifying existing operations in a state. How are you going to deal with that problem? </p>
  </blockquote>
  
  <p>I couldn't answer this question at that time. But later thought, I can probably:</p>
  
  <ul>
  <li>have different functions for different states (each function corresponding to a state)  </li>
  <li>have an <code>std::map</code> from (string, function) where string indicates state to call the corresponding state function.  </li>
  <li>The main function has a string variable (starting in initial state), and calls the function corresponding to that variable in a loop. Each function does the operations needed and returns the new state to the main function. </li>
  </ul>
  
  <p>My questions are:</p>
  
  <ul>
  <li>What is the problem with switch-case statements with respect to scalability in the context of large scale software systems?  </li>
  <li>If so is my solution (which currently I feel is a bit more modular than having long linear code) going to resolve the problem? </li>
  </ul>
  
  <p>The interview question is expecting answers from C++ idioms and design patterns for large scale software systems.</p>