Part 6 of 6 · 3 min read
Exercises
Easy
Easy 1: Spot the bug (20 minutes)
Write a constructor Meeting(String title, int start, int end, int people, boolean video, boolean recorded). Write a call with the two booleans swapped, and explain why the compiler accepts it.
Done when: you have the call and a one-line note on why a builder would prevent it.
Hint
Both parameters are boolean, so order does not matter to the compiler.
Easy 2: Run the builder (20 minutes)
Type the BookingRequest code and run the three calls of section 2.
Done when: you print the two requests and the message "catering needs 5 or more people".
Hint
The builder methods return this.
Easy 3: Choose the tool (20 minutes)
For each of these, say constructor, static factory, record or builder: a point with x and y; a duration made from minutes or hours; a server config with nine optional settings.
Done when: each has a choice and a reason.
Hint
A few fields need no builder.
Medium
Medium 1: Build a user profile (45 minutes)
Write an immutable Profile with name and email required, and phone, city and bio optional. Add a builder with a check that the email contains @.
Done when: a bad email is rejected in build and a good one gives an object with defaults.
Hint
Keep optional fields as String with an empty default.
Medium 2: Reuse a builder (45 minutes)
Use one builder to create two bookings by changing one setting between the calls. Add a serial number that rises with each build.
Done when: two objects print with serials 1 and 2 and different attendee counts.
Hint
A static counter in the Builder class works.
Medium 3: Add a rule (45 minutes)
Add the rule "a projector needs at least 3 attendees" to the booking builder and write three calls that test it.
Done when: one call passes, one fails on the new rule, and the old rule still works.
Hint
Add the check beside the catering check in build.
Hard
Hard 1: GoF builder with two outputs (90 minutes)
Extend the report example with an HtmlReport builder. Keep the director unchanged.
Done when: one director produces a text report and an HTML report.
Hint
The builder interface does not change, only a new class is added.
Hard 2: Hierarchy of builders (90 minutes)
Write an abstract Vehicle with a generic builder base and two subclasses, Car and Truck, each adding one extra option. Make the chain .wheels(4).seats(5).build() work for a car.
Done when: both subclasses build with the shared and the specific options, and no cast is needed.
Hint
The generic type is T extends Builder<T> with a self() method.
Hard 3: Compare four ways (90 minutes)
Write the same Server class with six fields using a telescoping constructor, setters, a builder and a record. Compare readability, safety and immutability.
Done when: a table has four rows and three columns and you choose one with reasons.
Hint
Count lines and the number of ways to call it wrongly.