Part 6 of 6 · 2 min read
Exercises
Easy
Easy 1: Draw the machine (20 minutes)
Draw the booking states as boxes and the events as arrows. Mark each arrow with the method name.
Done when: four boxes, five arrows, and the illegal moves listed beside the diagram.
Hint
Cancelled and checked-in have no outgoing arrows except to nowhere.
Easy 2: Run both versions (20 minutes)
Type the switch-style Booking and the State version. Run confirm, checkIn, then cancel on each.
Done when: both throw a message for cancel, and the State version prints "cannot cancel when CHECKED_IN".
Hint
The if version keeps the message in each method.
Easy 3: Count the conditions (20 minutes)
Count the if checks in the first version, and in the Booking class of the State version.
Done when: you have two numbers (and the second is zero).
Hint
The second count is zero because the state object decides.
Medium
Medium 1: Add a state (45 minutes)
Add a NO_SHOW state, reached from CONFIRMED by a new markNoShow() event. Change the fewest classes possible.
Done when: you list the files changed and the new class, and all earlier tests still pass.
Hint
One new class and one new method on State with a default.
Medium 2: Transition table (45 minutes)
Write the same booking as a Map<Status, Map<String, Status>>. Add a method fire(event).
Done when: the table gives the same results as the State classes for six event sequences.
Hint
Use Map.of for each row.
Medium 3: Enum machine (45 minutes)
Write the booking as an enum with a constant-specific next(event) method.
Done when: the enum version passes the same six sequences.
Hint
Each constant overrides next.
Hard
Hard 1: Gumball machine (90 minutes)
Build a machine with states no coin, has coin, sold and sold out, and actions insert coin, eject coin, turn crank. Use State classes.
Done when: a run of ten actions gives the expected states and refuses illegal moves with clear messages.
Hint
Sold out accepts nothing except a refill.
Hard 2: Behaviour in states (90 minutes)
Make states do real work: on confirm, send a message through an injected Notifier, and on cancel, refund through a Payments interface. Test with fakes.
Done when: a test checks one message after confirm and one refund after cancel.
Hint
States receive the dependencies in their constructors.
Hard 3: Choose the form (90 minutes)
Take a machine with six states and eight events. Write it three ways: State classes, a table and an enum. Compare lines, clarity and ease of adding a state.
Done when: a table has three columns and a chosen design with reasons.
Hint
Count how many files change for a seventh state.