Part 6 of 6 · 3 min read
Exercises
Easy
Easy 1: List the callers (20 minutes)
For the Place interface in section 2, write which caller uses which method. Mark every method that some caller never uses.
Done when: you have a table with callers as rows and methods as columns.
Hint
A scheduler uses only book.
Easy 2: Run the split (20 minutes)
Type the Room, Lobby, Scheduler and Menu code of section 2 and run it.
Done when: you print "Room, booked 2" and "Lobby".
Hint
Menu and Scheduler take the small interfaces.
Easy 3: Empty-method hunt (20 minutes)
Find three classes in code you wrote that have an empty method or one that throws "not supported". Write which interface forced it.
Done when: you have three entries with class, method and interface.
Hint
Look for throw new UnsupportedOperationException.
Medium
Medium 1: Split a repository (45 minutes)
A BookingRepository has save, findById, findAll, deleteAll and exportToCsv. Write three callers (a service, a report job and a test cleanup) and split the interface for them.
Done when: each caller depends on an interface with only the methods it uses.
Hint
A report job usually needs only the read methods.
Medium 2: Use two small interfaces (45 minutes)
Create a Printer interface with print, a Scanner interface with scan, and a class OfficeMachine that does both. Add a CheapPrinter that only prints.
Done when: CheapPrinter implements only Printer, and a method taking a Scanner rejects it at compile time.
Hint
A method that takes a Scanner will not compile with a CheapPrinter.
Medium 3: Role interfaces for a person (45 minutes)
A Staff class has getName, getSalary, approveLeave and bookRoom. Write the callers (payroll, manager screen, booking screen) and split the interfaces.
Done when: each screen sees only its methods, and the same Staff object is passed to all three.
Hint
Payroll needs name and salary.
Hard
Hard 1: Pick the cut lines (90 minutes)
Take a ten-method interface of your own (for example a MediaPlayer) and list five callers. Try two different splits and compare how many interfaces each needs and how many methods a caller sees.
Done when: a table compares both splits and you chose one with reasons.
Hint
Count the interfaces each caller must know.
Hard 2: Too many interfaces (90 minutes)
Split an interface into one interface per method. Count the interfaces. Argue what is lost, and write a better middle design.
Done when: you have both versions and a short note on readability against safety.
Hint
Look for callers that now need four interfaces together.
Hard 3: Dependency on a big library (90 minutes)
Pick a library you used. List the features you actually used and the features you did not. Draw a small interface of your own that wraps only the used part, and write a class that implements it with the library.
Done when: the rest of your code depends on your interface, and the library appears in one class only.
Hint
This is the same pattern as an adapter, covered in Level 4.