Part 6 of 6 · 2 min read
Exercises
Easy
Easy 1: List the checks (20 minutes)
For a transfer(from, to, amount) method, list every precondition and the standard exception for each.
Done when: at least four checks are listed with an exception name each.
Hint
Null, negative, same account and insufficient funds are a start.
Easy 2: Run the booking checks (20 minutes)
Type the Booking record and call it with null and with 12 hours.
Done when: you see the null message "room" and the text "hours must be 1 to 8: 12".
Hint
The record's compact constructor runs the checks.
Easy 3: Sort the errors (20 minutes)
Sort these into checked or unchecked, with a reason: file not found, negative price, network timeout, calling next() on an empty iterator.
Done when: four items each have a kind and a one-line reason.
Hint
Ask whether the caller can do something useful.
Medium
Medium 1: Busy room (45 minutes)
Write RoomBusyException with accessors, and a book method that throws it. In main, catch it and print a suggestion for the next free hour.
Done when: the program prints a different hour after a clash.
Hint
Keep a set of busy slots and scan forward.
Medium 2: Translate the store error (45 minutes)
Wrap a store that throws IllegalStateException and show that callers see only BookingFailedException with the original as the cause.
Done when: the output shows both messages and the caller code never names the store exception.
Hint
Pass the original as the second argument to the constructor.
Medium 3: Make it atomic (45 minutes)
Write a cancelAll(List<String> ids) that fails on the third id. Show the damage, then fix it so none are cancelled when one fails.
Done when: a test prints the count before and after for both versions.
Hint
Check all ids first, change state after.
Hard
Hard 1: Payment pipeline (90 minutes)
Design booking, payment and email steps. Say which failures are checked, which are unchecked, and what the caller sees. Write the code for the case where payment fails after the room is held.
Done when: a failed payment releases the hold, and a table lists each failure and its handling.
Hint
Hold, pay, confirm. Release the hold in the catch.
Hard 2: Remove the nulls (90 minutes)
Take a repository with find returning null and three callers. Change it to Optional and update the callers.
Done when: no caller has a null check, and one caller shows the case of an absent value.
Hint
Optional.ofNullable wraps the map lookup.
Hard 3: Exceptions in an API (90 minutes)
Write the public contract for a Wallet class: methods, preconditions, exceptions and what state remains after each failure.
Done when: every method has a @throws line and a note on failure atomicity, and a test checks two of them.
Hint
Document the state after failure, not only the exception.