Part 6 of 6 · 2 min read
Exercises
Easy
Easy 1: Find the common steps (20 minutes)
Write the steps for making tea and for making coffee. Mark which are the same and which differ.
Done when: a table lists each step with "same" or "differs".
Hint
Boiling water and pouring are the same for both.
Easy 2: Run the reports (20 minutes)
Type the report code and print both reports for the rows "A1 8" and "B2 3".
Done when: the output matches section 2.
Hint
rows.size() gives the total.
Easy 3: Try to break final (20 minutes)
Try to override generate in a subclass and read the compiler's message.
Done when: you have the error text and a one-line reason why final is useful.
Hint
The message mentions the overridden method being final.
Medium
Medium 1: Hot drink (45 minutes)
Write HotDrink with prepare() as the template method and Tea and Coffee subclasses. Add a hook wantsCondiments().
Done when: tea and coffee print their own steps, and one skips condiments through the hook.
Hint
The hook returns true or false.
Medium 2: Data import (45 minutes)
Write an Importer template: open, read each line, validate, store, close. Make CsvImporter and JsonLikeImporter.
Done when: both subclasses run through the same final method and print stored counts.
Hint
Close the resource in a finally block.
Medium 3: Show the trap (45 minutes)
Reproduce the constructor trap with a parent that calls an overridable method. Fix it by moving the call out of the constructor.
Done when: you show "null" before the fix and the right value after.
Hint
Make a separate start() method that callers invoke.
Hard
Hard 1: Lambda version (90 minutes)
Rewrite Report as a class that takes header and formatRow as functions. Compare with the inheritance version.
Done when: a table compares lines, flexibility and risks, and you pick one.
Hint
Use Function<String, String> for each step.
Hard 2: Test framework (90 minutes)
Build a mini test runner with setUp, test and tearDown as the template. Run three test classes, and make sure tearDown runs even if the test throws.
Done when: a failing test still runs tearDown, and a summary prints pass and fail counts.
Hint
Wrap the test call in try and finally.
Hard 3: Too many steps (90 minutes)
Take a template with eight abstract steps. Group them, replace some with hooks, and move others into collaborators. Explain each change.
Done when: the new version has at most three abstract steps, with a reason for each change.
Hint
A step that rarely changes can be a hook.