This was an interview question to be coded in C++:
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.
My answer:
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.
The next question:
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?
I couldn't answer this question at that time. But later thought, I can probably:
- have different functions for different states (each function corresponding to a state)
- have an
std::map
from (string, function) where string indicates state to call the corresponding state function. - 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.
My questions are:
- What is the problem with switch-case statements with respect to scalability in the context of large scale software systems?
- If so is my solution (which currently I feel is a bit more modular than having long linear code) going to resolve the problem?
The interview question is expecting answers from C++ idioms and design patterns for large scale software systems.
Best Answer
I was thinking in a more OO approach, using the
State Pattern
:The Machine:
The States:
I'm not used to program in C++, but this code apparently compiles against
GCC 4.8.2clang
@11.0.0
and Valgrind shows no leaks, so I guess it's fine. I'm not computing money, but I don't need this to show you the idea.To test it:
A little bit of
Makefile
:Then run:
Output is:
Now, if you want to add a
Broken
state, all you need is anotherAbstractState
child:To add more products, you must have a map of products and its respective in-stock quantity and so on...
The final code can be found in this repo.