CSE Roadmap

Core tier · about 4 hours · 6 parts

Part 4 of 6 · 5 min read

The code

Borrow, return, renew.

The value and entity classes are small. The Loan holds its dates and changes only through renew and close:

record Book(String isbn, String title, String author) {}

class Loan {
    private final Copy copy; private final Member member;
    private LocalDate due; private int renewals; private LocalDate returned;
    boolean open()                  { return returned == null; }
    void renew(int days)            { due = due.plusDays(days); renewals++; }
    void close(LocalDate d)         { returned = d; }
    // constructor and getters omitted
}

interface FinePolicy { long fine(LocalDate due, LocalDate returned); }

class PerDayFine implements FinePolicy {
    private final long rate, cap;
    public long fine(LocalDate due, LocalDate ret) {
        long late = Math.max(0, ChronoUnit.DAYS.between(due, ret));
        return Math.min(cap, late * rate);
    }
}

The borrow method applies the rules in a fixed order. Every check comes before any change.

Loan borrow(String memberId, String isbn) throws LibraryException {
    Member m = members.get(memberId);
    if (m == null) throw new NoSuchElementException("no member " + memberId);
    if (unpaid.getOrDefault(memberId, 0L) > 0)
        throw new LibraryException("unpaid fines " + unpaid.get(memberId));
    if (openLoans(m) >= MAX_LOANS) throw new LibraryException("loan limit reached");
    if (hasOpenLoanFor(m, isbn))   throw new LibraryException("already has this title");

    Deque<Member> q = holds.getOrDefault(isbn, new ArrayDeque<>());
    Copy free = firstAvailableCopy(isbn);
    if (free == null) {                                   // all copies out: join the queue
        holds.computeIfAbsent(isbn, k -> new ArrayDeque<>());
        if (!holds.get(isbn).contains(m)) holds.get(isbn).add(m);
        throw new LibraryException("no copy free, hold placed at position " + holds.get(isbn).size());
    }
    if (!q.isEmpty() && !q.peekFirst().equals(m))
        throw new LibraryException("copy is held for another member");
    if (!q.isEmpty()) q.pollFirst();                      // this member was first in line
    free.setOnLoan(true);
    Loan l = new Loan(free, m, clock.today().plusDays(LOAN_DAYS));
    loans.add(l);
    return l;
}

An unknown member id is a caller mistake, so it throws an unchecked exception. A refusal such as the loan limit is a normal business outcome that the desk can explain to the member, so it is a checked LibraryException (Level 5, module 1). The refusal that places a hold is unusual. The call fails as a borrow, but it also changes state, since the hold is stored. Say that aloud, and consider returning a result object with the values BORROWED and HELD instead, which would remove the oddity.

Return and renew:

long giveBack(String copyId) {
    Loan l = openLoanOf(copyId);                 // NoSuchElementException if not on loan
    l.close(clock.today()); l.copy().setOnLoan(false);
    long f = fines.fine(l.due(), l.returned());
    if (f > 0) unpaid.merge(l.member().id(), f, Long::sum);
    return f;
}

void renew(String copyId) throws LibraryException {
    Loan l = openLoanOf(copyId);
    if (l.renewals() >= MAX_RENEWALS) throw new LibraryException("already renewed");
    if (!holds.getOrDefault(l.copy().book().isbn(), new ArrayDeque<>()).isEmpty())
        throw new LibraryException("another member is waiting");
    if (l.due().isBefore(clock.today())) throw new LibraryException("overdue, return it");
    l.renew(RENEW_DAYS);
}

A run: three members (asha, ravi, meera), five copies of four titles (two copies of "Effective Java"), and a clock on 1 March 2026:

Action Result
Search "java"; search "martin" one title; one title
Asha borrows "Clean Code" due 15 March
Ravi borrows it; Meera borrows it "no copy free, hold placed at position 1"; then position 2
Asha renews "another member is waiting"
20 days pass; Asha returns it fine 12 (6 late days at 2)
Asha borrows a title "unpaid fines 12"
Meera borrows "Clean Code" "copy is held for another member" (Ravi is first)
Ravi borrows it gets the copy c1
Asha pays her fine, then borrows three titles all three succeed
Asha borrows a fourth "loan limit reached"
Ravi borrows "Effective Java" twice the second says "already has this title"
Asha renews a loan, then again the second says "already renewed"
60 more days pass; she returns it fine 50, the cap (39 late days at 2 would be 78)

Check yourself: 1. Which checks come first in borrow, and why before the queue? 2. Why does Meera get "held for another member" when a copy is free? 3. What is the fine for 39 late days with this policy?