Part 7 of 7 · 2 min read
Exercises
Easy
Easy 1: Lowest access (20 minutes)
Take a class with five public fields and three public methods. Choose the lowest access level for each and say why.
Done when: an eight-row table.
Hint
Fields are private, and only the methods callers need are public.
Easy 2: Find the invariants (20 minutes)
List one invariant for each of: a stack with a maximum size, a booking, a shopping cart, a seat.
Done when: four invariants.
Hint
An invariant is true after every method.
Easy 3: Setter or not (20 minutes)
For Account, Room and Booking, say which fields should have a setter, with a reason.
Done when: a three-row table.
Hint
A setter is a risk to a rule.
Medium
Medium 1: Break and fix (30 minutes)
Write Account with a public balance field. Write code that makes it negative. Then fix the class.
Done when: a failing version and a passing version.
Hint
Assign -5 directly to the field.
Medium 2: Defensive copy (30 minutes)
Write a class Team that stores a List<String> of members. Show how a caller can change it from outside, then fix it with a copy in the constructor and in the getter.
Done when: a demonstration of the bug and the fixed code.
Hint
Use List.copyOf in both places.
Medium 3: Make it immutable (30 minutes)
Make a Version class with major, minor and patch immutable. Add bumpMinor() that returns a new version.
Done when: code that follows all five rules, with each rule marked in a comment.
Hint
Mark the class final and every field private final.
Hard
Hard 1: Tell, do not ask (45 minutes)
Refactor a small order class that has getItems(), getTotal() and setStatus() called by outside code. Move the rules inside.
Done when: the outside code calls only addItem, pay and cancel.
Hint
The order checks its own status before accepting an item.
Hard 2: Hidden representation (45 minutes)
Write a TimeOfDay class that stores minutes from midnight, then change it to store hours and minutes without changing any caller.
Done when: two internal versions with the same public methods and the same tests.
Hint
Keep a method such as totalMinutes() stable.
Hard 3: Immutability cost (50 minutes)
Build a string of 100,000 characters by repeated concatenation of an immutable String, and again with a StringBuilder. Compare the time and explain the trade-off.
Done when: two timings and a paragraph on when immutability is worth its cost.
Hint
Use System.nanoTime() around each loop.