Part 6 of 6 · 2 min read
Exercises
Easy
Easy 1: Draw the state table (20 minutes)
Draw a table with rows for states and columns for insert, select and cancel, for a machine with Idle, HasMoney and OutOfService.
Done when: nine cells are filled, and OutOfService refuses all three actions.
Hint
OutOfService refuses everything, so the cells are messages.
Easy 2: Run the table (20 minutes)
Type the code and reproduce the run table in section 3.
Done when: all nine rows match.
Hint
Build the inventory and the bank first, then the machine.
Easy 3: Change by hand (20 minutes)
With coins 10, 5, 2 and 1, and a stock of one 5 and three 2s, work out change for 6, 7 and 9 by hand.
Done when: three answers (2+2+2, 5+2, 5+2+2) are written, and you say which one greedy misses.
Hint
For 6, greedy takes the 5 and is stuck.
Medium
Medium 1: Out of service (45 minutes)
Add an OutOfService state and an admin method to switch to it and back. Do not edit Idle or HasMoney.
Done when: all three actions are refused in that state, and returning to Idle works.
Hint
The admin method sets the state directly.
Medium 2: Test the refusal (45 minutes)
Write a test for the "cannot give change" sale that checks stock, bank counts and balance before and after.
Done when: all three values are the same before and after, and a cancel returns the coins.
Hint
Compare bank.count(d) for each coin size.
Medium 3: Price strategy (45 minutes)
Add a PriceStrategy so that the price depends on a rule, such as a discount after 6 pm using an injected clock.
Done when: the same item costs two different amounts at two times, and HasMoney calls the strategy.
Hint
Inject the clock into the strategy and not into the machine.
Hard
Hard 1: Enum states (90 minutes)
Rewrite the machine with an enum for the state and a transition table, as in Level 4, module 3. Compare with the classes version.
Done when: both versions pass the same tests, and a note compares lines of code and how a new state is added.
Hint
A Map<State, Map<Event, State>> holds the table.
Hard 2: Concurrency (90 minutes)
Run 20 threads, each inserting coins and selecting. Show that balance never goes negative and that the bank's total value stays consistent.
Done when: a check at the end shows that coins in the bank equal initial coins plus received minus change given.
Hint
Use a start latch, and make the machine's methods synchronized.
Hard 3: Save and restore (90 minutes)
Save the machine to text (state name, balance, inserted coins, stock, bank) and rebuild it. Test that a rebuilt machine continues a sale correctly.
Done when: a machine saved in HasMoney with a balance of 10 completes the sale after being restored.
Hint
A text line per field is enough.