Part 6 of 6 · 2 min read
Exercises
Easy
Easy 1: Find the new (20 minutes)
Look at three classes you wrote. Mark each line that creates another class with new. Say which of these are volatile details.
Done when: you have a list of lines with a note on each: stable or volatile.
Hint
Standard library classes such as String and List are usually stable.
Easy 2: Run both versions (20 minutes)
Type the ServiceBefore and the BookingService code and run them with SMTP and SMS.
Done when: you print "SMTP to asha: Booked" and "SMS to asha: Booked".
Hint
The service constructor needs the Notifier value.
Easy 3: Draw the arrows (20 minutes)
Draw the before and after versions with boxes and arrows from source dependencies.
Done when: the before drawing has one arrow from service to detail, and the after drawing has the detail's arrow pointing at the interface.
Hint
Arrows show "knows about" in the source code.
Medium
Medium 1: Clock as a dependency (45 minutes)
A Booking class calls LocalDateTime.now() inside. Replace it with a Clock interface passed in, and write a test with a fixed time.
Done when: a test checks a booking made at 10:00 without waiting for 10:00.
Hint
The interface has one method, now().
Medium 2: Swap the store (45 minutes)
Write BookingRepository as an interface with an in-memory class and a file-backed class. Make BookingService depend on the interface.
Done when: the service runs with either store and its code is unchanged.
Hint
Use the same test over both stores.
Medium 3: Write the test (45 minutes)
Using FakeNotifier, write a test that checks that confirm sends exactly one message with the right text.
Done when: the test fails if confirm sends twice or sends the wrong text.
Hint
Count entries in the fake's list.
Hard
Hard 1: Own the interface (90 minutes)
Wrap a fictional payment vendor whose methods are chargeCardV2(String number, long cents) and refundV2(String txn). Write an interface Payments from your service's view, and an adapter class.
Done when: the service has no mention of the vendor's names.
Hint
The adapter translates dollars and names into the vendor's units and methods.
Hard 2: Where does new happen? (90 minutes)
Build a small program with three services and two details. Put all new calls in one main or Config class. Draw which classes know which concrete classes.
Done when: only the config class names concrete classes, and the services compile without them.
Hint
Your service constructors take interfaces only.
Hard 3: When not to invert (90 minutes)
Make a list of ten dependencies in a program you know. Mark each as "invert" or "leave", with a reason (stable, volatile, tested, likely to change).
Done when: you have ten reasoned decisions and one you changed your mind on.
Hint
Ask what would force a rewrite if it changed.