Part 6 of 6 · 2 min read
Exercises
Easy
Easy 1: List the dependencies (20 minutes)
Take a class of your own and list every other class it creates with new or reads from a static field.
Done when: you have a list and mark which ones you would inject.
Hint
Anything that uses new, a static call or a global is a candidate.
Easy 2: Run the wiring (20 minutes)
Type the BookingService and main code and run it.
Done when: you print "notify asha: booked at 1000" and 1.
Hint
Order matters when building: store, then service.
Easy 3: Spot the hidden one (20 minutes)
Write a method that calls LocalDateTime.now() inside. Make the time a parameter or a Clock dependency.
Done when: both versions exist and the second can be tested at a fixed time.
Hint
Clock with one method works well with a lambda.
Medium
Medium 1: Convert a class (45 minutes)
Take a class that creates its own EmailSender and a Database inside its constructor. Change it to constructor injection with interfaces.
Done when: the class has no new of a real dependency and a test passes fakes.
Hint
Interfaces go on the side of the dependency.
Medium 2: Write the fakes (45 minutes)
For BookingService, write the test with the lambda clock, the list-backed notifier and a memory store. Add a second test where the store is empty.
Done when: two tests pass and check the exact message text.
Hint
A lambda can stand in for a one-method interface.
Medium 3: Supplier of objects (45 minutes)
Write TicketMachine that needs a new Ticket for each sale. Inject a Supplier<Ticket> and show that two sales give different tickets.
Done when: the machine never names the Ticket implementation.
Hint
Supplier<Ticket> is Ticket::new.
Hard
Hard 1: Compose a bigger graph (90 minutes)
Build a program of six classes with at least eight dependencies. Wire it in a main of under 30 lines.
Done when: only main uses new on concrete service classes, and a diagram shows the arrows pointing away from main.
Hint
Build leaves first, then the classes that need them.
Hard 2: Two configurations (90 minutes)
Write two composition roots, one for production and one for a demo with fakes. Run the same service with both.
Done when: the service class is unchanged and the output differs.
Hint
Two main methods or two factory methods.
Hard 3: Hand-made versus framework (90 minutes)
Wire the same small program by hand and with a small DI container you write (a Map<Class, Supplier>). Compare effort and readability.
Done when: both work, and a note lists what the container adds and what it hides.
Hint
A container is a map plus a recursive lookup.