Part 6 of 6 · 2 min read
Exercises
Easy
Easy 1: Write the rules (20 minutes)
Write seven numbered requirements for a library and three questions you would ask.
Done when: seven rules and three questions exist, and two features are marked out of scope.
Hint
Think about what the member and the desk each do.
Easy 2: Run the desk (20 minutes)
Type the code and reproduce the first five rows of the run table.
Done when: you print the due date, two hold positions and the "another member is waiting" refusal.
Hint
Create the clock first, and move it with a method.
Easy 3: Fines by hand (20 minutes)
With a rate of 2 per day and a cap of 50, work out the fine for returns 0, 1, 10, 25 and 40 days late.
Done when: five answers (0, 2, 20, 50, 50) are written with the rule used.
Hint
Subtract days late times 2 from the cap with Math.min.
Medium
Medium 1: Result object (45 minutes)
Change borrow to return a BorrowResult with the values BORROWED(loan) and HELD(position), and use exceptions only for real refusals.
Done when: the hold case no longer throws and all earlier tests pass with small changes.
Hint
A small record or sealed interface works.
Medium 2: Loan policy (45 minutes)
Add a LoanPolicy with the loan length and the limit, chosen by member type (student, staff). Remove the constants from Library.
Done when: a student gets 14 days and three loans, and a staff member gets 28 days and five.
Hint
The member type is a value on Member.
Medium 3: Fast lookups (45 minutes)
Add maps from copy id to open loan and from member id to open loans. Keep all tests passing.
Done when: no method scans the full loan list, and a test with 10,000 loans runs fast.
Hint
Update both maps whenever a loan opens or closes.
Hard
Hard 1: Hold deadlines (90 minutes)
Give each hold a ready date. When a copy returns, the head of the queue has 3 days to borrow it, after which the next member gets it.
Done when: a test moves the clock past the deadline and the next member in line can borrow.
Hint
Store the ready date on the queue entry.
Hard 2: Threads (90 minutes)
Run 20 threads that each try to borrow the last copy of a title. Make Library safe and prove it.
Done when: exactly one thread succeeds in 200 repeated runs, and 19 are queued in order.
Hint
synchronized on the public methods is the simplest fix.
Hard 3: Notifications (90 minutes)
Add events for "copy returned" and "hold ready". Write a listener that sends a message through a notifier interface, and test it with a fake.
Done when: a return with a queue sends one message to the first member only, and Library does not name the listener class.
Hint
Publish an event object with the title and the member.