Part 6 of 6 · 2 min read
Exercises
Easy
Easy 1: Draw the chain (20 minutes)
Draw the three approvers as boxes with arrows. Mark where requests of 3000, 12000, 90000 and 250000 stop.
Done when: four requests are traced on the diagram.
Hint
Each handler either handles or forwards.
Easy 2: Run the chain (20 minutes)
Type the approver code and run the four amounts.
Done when: you print "lead approved 3000", "manager approved 12000", "director approved 90000" and "nobody approved 250000".
Hint
then returns the new handler so you can chain calls.
Easy 3: Run the checks (20 minutes)
Type the validation list and run the three requests of section 4.
Done when: the output reads "hours must be positive", "payment missing" and "accepted".
Hint
A check returns null when the request passes.
Medium
Medium 1: Add a vice president (45 minutes)
Insert a vice president with a 50000 limit between the manager and the director. Do not edit the other classes.
Done when: a request for 30000 is approved by the vice president.
Hint
Call then in the new order.
Medium 2: Default handler (45 minutes)
Add a final handler that rejects with the text "needs board approval". Remove the null check for the missing successor and show that it is no longer needed.
Done when: 250000 returns "needs board approval" with no special case in handle.
Hint
A handler whose canApprove always returns true.
Medium 3: Support tickets (45 minutes)
Write a chain of level 1, level 2 and level 3 support, where each handles tickets up to a certain difficulty number.
Done when: five tickets of different difficulty reach the right level.
Hint
A ticket carries a difficulty number.
Hard
Hard 1: Request filters (90 minutes)
Build a mini web pipeline with filters for authentication, logging and compression. Each may call the next one or stop. Make logging record both before and after the rest of the chain.
Done when: a log shows "start" and "end" around the handler, and a failed authentication stops everything.
Hint
Pass the next filter into each filter as an argument.
Hard 2: Collect all errors (90 minutes)
Change the validation chain so that it collects every error, not only the first. Compare the two versions.
Done when: a bad request returns three messages, and a table compares the versions.
Hint
Add each error to a list and return the list.
Hard 3: Chain or if (90 minutes)
Decide whether the approval problem needs a chain or a single method with a sorted list of limits. Write both and compare.
Done when: a note picks one with reasons, and names the change that would reverse your choice.
Hint
A sorted list of limits is a loop with one if.