SyntaxPilot
Courses/Low-Level Design/Lesson 73
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Low-Level Design · Lesson 73 of 90

Design a library management system

library requirementsBook vs BookItemMemberLibrarianCatalogsearch by title author subjectlendingreturndue datesfinesreservationsholds queueaccount statusnotifications on availability

These are the notes for Low-Level Design (LLD) episode 73: designing a library management system, one of the most common machine-coding questions. We start with code that keeps a count of books per title, watch it lose track of who has what, and fix one problem at a time: Book vs BookItem, a Catalog you can search by title, author and subject, Member and Librarian, lending and returns with due dates, fines and account status, and finally reservations with a holds queue and notifications on availability.

How the code was run: every program was saved as Main.java in a fresh folder and run with javac Main.java && java -cp . Main on OpenJDK 21. Every output below is the real output, pasted exactly. Members, barcodes, ISBNs and fines are made up for teaching. The two book titles are real books: Clean Code by Robert C. Martin, and Wings of Fire, the autobiography of A P J Abdul Kalam (written with Arun Tiwari).

1. The problem: the school library

School library Library management system
One line in the register per title: "Clean Code, 2 copies" A Book (the title)
A number stamped inside every copy: B-101, B-102 A BookItem (one physical copy)
Card drawers sorted by title, author, subject The Catalog and its indexes
A due-date stamp; pay if you're late A Loan with a due date, and a fine
No more books until you pay Account status: BLOCKED
A waiting list at the desk Reservations and a holds queue
"Your book is here" A notification on availability

2. Requirements: the words

In a machine-coding round you first agree on the requirements: the things the system must do. Writing them down stops you from building the wrong thing.

  • Member: a person who borrows books. Has a name, loans and a fine.
  • Librarian: the person (or desk) who lends and takes books back. In code, the class that holds the lending rules.
  • Catalog: the list of every book the library owns, searchable.

Our requirements:

  1. Search books by title, author or subject.
  2. Lend a copy for 14 days; return it.
  3. A fine of 5 rupees for every day late.
  4. At most 2 books per member; block a member who owes 50 rupees or more.
  5. If no copy is free, the member can reserve the title and is told when a copy is ready.

These numbers are our own choices for the exercise. In an interview, ask: "How long is a loan? Is there a limit? What is the fine?" and write the answers down.

3. Attempt 1: a count per title

import java.util.*;
class Library {                                     // attempt: one count per title
    Map<String, Integer> copies = new HashMap<>(Map.of("Clean Code", 2, "Wings of Fire", 1));
    Map<String, String> borrowedBy = new HashMap<>();   // title -> member ... only ONE?
    void lend(String title, String member) {
        if (copies.get(title) == 0) { System.out.println("  " + title + ": none left"); return; }
        copies.put(title, copies.get(title) - 1);
        borrowedBy.put(title, member);
        System.out.println("  lent " + title + " to " + member);
    }
    void giveBack(String title) { copies.put(title, copies.get(title) + 1); }
}
public class Main { public static void main(String[] args) {
    Library lib = new Library();
    lib.lend("Clean Code", "Asha");
    lib.lend("Clean Code", "Ravi");
    System.out.println("who has Clean Code? " + lib.borrowedBy.get("Clean Code"));
    lib.giveBack("Clean Code");  lib.giveBack("Clean Code");
    lib.giveBack("Clean Code");                     // a donated book, returned by mistake
    System.out.println("copies of Clean Code: " + lib.copies.get("Clean Code") + " (we own 2)");
    lib.lend("Gitanjali", "Neha");                  // a title we don't have
} }

Real output:

  lent Clean Code to Asha
  lent Clean Code to Ravi
who has Clean Code? Ravi
copies of Clean Code: 3 (we own 2)
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.Map.get(Object)" is null
    at Library.lend(Main.java:6)
    at Main.main(Main.java:21)

Why it failed

  • Who has Clean Code? Ravi. But Asha has a copy too. borrowedBy maps a title to one name, so the second put overwrote the first.
  • copies of Clean Code: 3 (we own 2). A count can't tell copies apart, so any return adds one, even a book we never lent.
  • A title we don't own crashes. copies.get("Gitanjali") returns null, and unboxing null to an int throws a NullPointerException.

The root cause: a title is not a copy.

4. The fix: Book vs BookItem, and a Catalog

  • Book: the title. One per ISBN (International Standard Book Number, the number printed on the back of a book; ours are short made-up ones like ISBN-1). It holds title, author and subject. It's a record: a class that only holds values, with equals, hashCode and toString written for you.
  • BookItem: one physical copy. It has its own barcode (the sticker the scanner reads, like B-101) and its own status.
  • ItemStatus: an enum (a fixed list of named values): AVAILABLE, LOANED, ON_HOLD.
  • Catalog: keeps an index per field. An index is a lookup table, like the index at the back of a textbook: a word, and where to find it. Here: field → text (lower case) → list of books. A search is two map lookups instead of a loop over every book.
import java.util.*;
enum ItemStatus { AVAILABLE, LOANED, ON_HOLD }
record Book(String isbn, String title, String author, String subject) {}  // the title: one per ISBN
class BookItem {                                        // one physical copy, with its own barcode
    final String barcode;  final Book book;  ItemStatus status = ItemStatus.AVAILABLE;
    BookItem(String barcode, Book book) { this.barcode = barcode;  this.book = book; }
    public String toString() { return barcode + " " + status; } }
class Catalog {                                         // search by title, author or subject
    private final Map<String, Map<String, List<Book>>> index = new HashMap<>();  // field -> text -> books
    private final Map<String, List<BookItem>> copies = new HashMap<>();         // isbn -> its copies
    void add(Book b, String... barcodes) {
        String[][] fields = {{"title", b.title()}, {"author", b.author()}, {"subject", b.subject()}};
        for (String[] f : fields) index.computeIfAbsent(f[0], k -> new HashMap<>())
                                       .computeIfAbsent(f[1].toLowerCase(), k -> new ArrayList<>()).add(b);
        for (String c : barcodes)
            copies.computeIfAbsent(b.isbn(), k -> new ArrayList<>()).add(new BookItem(c, b)); }
    List<Book> search(String field, String q) {
        return index.get(field).getOrDefault(q.toLowerCase(), List.of()); }
    List<BookItem> copiesOf(Book b) { return copies.get(b.isbn()); } }
public class Main { public static void main(String[] args) {
    Catalog cat = new Catalog();
    cat.add(new Book("ISBN-1", "Clean Code", "Robert Martin", "Programming"), "B-101", "B-102");
    cat.add(new Book("ISBN-2", "Wings of Fire", "A P J Abdul Kalam", "Biography"), "B-201");
    for (Book b : cat.search("subject", "programming"))
        System.out.println(b.title() + " -> " + cat.copiesOf(b));
    System.out.println("author kalam: " + cat.search("author", "a p j abdul kalam").get(0).title());
    System.out.println("title gitanjali: " + cat.search("title", "Gitanjali"));
} }

Real output:

Clean Code -> [B-101 AVAILABLE, B-102 AVAILABLE]
author kalam: Wings of Fire
title gitanjali: []
  • Searching the Book finds the title; the copies list tells you which physical copies exist and their status.
  • A missing title is now an empty list, not a crash (getOrDefault).
  • One relationship to remember: one Book has many BookItems (1 to *).

5. Lending and returns: Member, Librarian, Loan, fines, account status

  • Loan: which copy, which member, and the due date (the day you borrow + 14 days).
  • Fine: days late × 5 rupees, never negative.
  • FinePolicy: an interface with one method, int fine(long daysLate). This is the Strategy pattern (episode 34): the fine rule can change (students pay less, weekends don't count) without editing the desk.
  • AccountStatus: ACTIVE, or BLOCKED once the fine due is 50 or more.
  • Librarian.lend checks, in order: is the member blocked? are they at the limit? is the copy free?
  • Librarian.giveBack frees the copy, adds the fine and blocks the member if needed.
import java.time.*;  import java.time.temporal.ChronoUnit;  import java.util.*;
enum AccountStatus { ACTIVE, BLOCKED }      record Loan(BookItem item, Member member, LocalDate due) {}
class BookItem { final String barcode;  boolean loaned;  BookItem(String b) { barcode = b; } }
class Member { final String name;  int fineDue;  AccountStatus status = AccountStatus.ACTIVE;
    final List<Loan> loans = new ArrayList<>();  Member(String n) { name = n; } }
interface FinePolicy { int fine(long daysLate); }              // Strategy: change the rule, not the desk
class Librarian {                                              // the lending desk
    static final int MAX_BOOKS = 2, LOAN_DAYS = 14, BLOCK_AT = 50;
    final FinePolicy policy = days -> (int) Math.max(0, days) * 5;   // 5 rupees a day late
    Loan lend(BookItem item, Member m, LocalDate today) {
        if (m.status == AccountStatus.BLOCKED) throw new IllegalStateException(m.name + " is BLOCKED");
        if (m.loans.size() >= MAX_BOOKS) throw new IllegalStateException("limit reached");
        if (item.loaned) throw new IllegalStateException(item.barcode + " is already loaned");
        item.loaned = true;  Loan l = new Loan(item, m, today.plusDays(LOAN_DAYS));
        m.loans.add(l);  return l; }
    void giveBack(Loan l, LocalDate today) {
        int fine = policy.fine(ChronoUnit.DAYS.between(l.due(), today));
        l.item().loaned = false;  l.member().loans.remove(l);  l.member().fineDue += fine;
        if (l.member().fineDue >= BLOCK_AT) l.member().status = AccountStatus.BLOCKED;
        System.out.println(l.item().barcode + " back " + today + ", due " + l.due() + ", fine " + fine); } }
public class Main { public static void main(String[] args) {
    Librarian desk = new Librarian();  Member asha = new Member("Asha");
    BookItem b101 = new BookItem("B-101"), b201 = new BookItem("B-201");
    Loan l1 = desk.lend(b101, asha, LocalDate.of(2026, 11, 2));
    Loan l2 = desk.lend(b201, asha, LocalDate.of(2026, 11, 2));
    desk.giveBack(l1, LocalDate.of(2026, 11, 10));             // early: no fine
    desk.giveBack(l2, LocalDate.of(2026, 11, 28));             // 12 days late
    System.out.println(asha.name + ": fine " + asha.fineDue + ", status " + asha.status);
    desk.lend(b101, asha, LocalDate.of(2026, 11, 28)); } }

Real output:

B-101 back 2026-11-10, due 2026-11-16, fine 0
B-201 back 2026-11-28, due 2026-11-16, fine 60
Asha: fine 60, status BLOCKED
Exception in thread "main" java.lang.IllegalStateException: Asha is BLOCKED
    at Librarian.lend(Main.java:11)
    at Main.main(Main.java:29)
  • Both books were due on 16 November (2 November + 14 days).
  • B-101 came back early: ChronoUnit.DAYS.between(due, today) is negative, and Math.max(0, days) makes the fine 0.
  • B-201 came back 12 days late: 12 × 5 = 60 rupees, which is ≥ 50, so Asha is BLOCKED, and the next lend throws IllegalStateException: Asha is BLOCKED.

Java words used here:

  • LocalDate: a date without a time, like 2026-11-02. plusDays(14) gives a new date.
  • ChronoUnit.DAYS.between(a, b): the number of days from a to b (negative if b is earlier).
  • IllegalStateException: "the input is fine, but the object's current state doesn't allow this".
  • A lambda (days -> ...): a short function written inline; here it implements FinePolicy.

6. Reservations: a holds queue and notifications

When every copy is out, a member makes a reservation: "give me the next free copy". Reservations wait in a holds queue, which is FIFO (first in, first out): whoever reserved first is served first.

When a copy comes back and someone is waiting, it is not put back on the shelf. It becomes ON_HOLD, kept for the first member in the queue, and that member is told. We tell them with the Observer pattern (episode 35): the desk keeps a list of listeners (an SMS sender, an email sender) and calls every one of them.

import java.util.*;  import java.util.function.Consumer;
enum ItemStatus { AVAILABLE, LOANED, ON_HOLD }
class BookItem { final String barcode;  ItemStatus status = ItemStatus.AVAILABLE;  String heldFor;
    BookItem(String b) { barcode = b; } }
class Title {                                             // one book title: its copies + a holds queue
    final String name;  final List<BookItem> copies = new ArrayList<>();
    final List<String> holds = new LinkedList<>();        // FIFO: first to reserve, first served
    Title(String n, String... codes) { name = n;  for (String b : codes) copies.add(new BookItem(b)); } }
class Desk {
    final List<Consumer<String>> listeners = new ArrayList<>();   // Observer: who wants to hear about it
    String borrow(Title t, String m) {
        for (BookItem c : t.copies)
            if (c.status == ItemStatus.AVAILABLE || (c.status == ItemStatus.ON_HOLD && m.equals(c.heldFor))) {
                c.status = ItemStatus.LOANED;  c.heldFor = null;  return m + " got " + c.barcode; }
        if (!t.holds.contains(m)) t.holds.add(m);                 // no copy free: join the queue once
        return m + " waits for " + t.name + ", position " + (t.holds.indexOf(m) + 1); }
    void giveBack(Title t, BookItem c) {
        if (t.holds.isEmpty()) { c.status = ItemStatus.AVAILABLE;  return; }
        String next = t.holds.remove(0);
        c.status = ItemStatus.ON_HOLD;  c.heldFor = next;         // kept aside for the first in line
        listeners.forEach(l -> l.accept(next + ": " + t.name + " (" + c.barcode + ") is ready")); } }
public class Main { public static void main(String[] args) {
    Title cc = new Title("Clean Code", "B-101");  Desk desk = new Desk();
    desk.listeners.add(msg -> System.out.println("  SMS   -> " + msg));
    desk.listeners.add(msg -> System.out.println("  EMAIL -> " + msg));
    for (String m : List.of("Asha", "Ravi", "Neha")) System.out.println(desk.borrow(cc, m));
    desk.giveBack(cc, cc.copies.get(0));                          // Asha returns it
    System.out.println(desk.borrow(cc, "Neha"));                  // Neha tries to jump the queue
    System.out.println(desk.borrow(cc, "Ravi")); } }

Real output:

Asha got B-101
Ravi waits for Clean Code, position 1
Neha waits for Clean Code, position 2
  SMS   -> Ravi: Clean Code (B-101) is ready
  EMAIL -> Ravi: Clean Code (B-101) is ready
Neha waits for Clean Code, position 1
Ravi got B-101
  • Asha got the only copy; Ravi is position 1, Neha position 2.
  • When Asha returned it, both listeners told Ravi it is ready.
  • Neha could not take it: it is ON_HOLD for Ravi, so she is told she's now position 1.
  • Ravi then collected his book.

7. The class diagram

Catalog: index[title | author | subject] ─▶ List<Book>       isbn ─▶ List<BookItem>
Book (record: isbn, title, author, subject)  1 ──── *  BookItem (barcode, status, heldFor)
  ItemStatus: AVAILABLE ─lend─▶ LOANED ─return─▶ AVAILABLE | ON_HOLD (first in the holds queue)
Member (name, loans, fineDue, AccountStatus ACTIVE | BLOCKED)  1 ──── *  Loan (item, member, due)
Librarian / Desk: lend() checks status, MAX_BOOKS, copy free · giveBack() ─▶ FinePolicy (Strategy)
Title.holds: FIFO queue of members ─▶ listeners (Observer): SMS, EMAIL "is ready"
  • Book 1 ── * BookItem: one title, many copies.
  • Member 1 ── * Loan: a member can have several loans (at most MAX_BOOKS).
  • The Librarian is the only class that changes item status and fines, so every rule lives in one place.

8. Interview follow-ups

Question Answer
A hold nobody collects? Give it an expiry (say 3 days), then offer the copy to the next in line. A scheduler (episode 71) can sweep expired holds. See the mini project.
Renewing a loan? Allow it only if nobody is waiting in that title's holds queue, and only a limited number of times.
A lost book? A new status LOST; charge the book's price; remove it from the copy list.
Two desks lend the same copy at the same moment? Make the "is it free? then take it" step atomic: synchronized on the copy, or a compare-and-set on its status (episode 75 shows the same problem for cinema seats).
Search by part of a title? Index every word of the title, not the whole title (the mini project does this).
Many branches? Add a Branch to each BookItem; search shows which branch has a free copy.

9. Common mistakes

Mistake What you see (real) Fix
A count per title copies of Clean Code: 3 (we own 2) Book + BookItem
One borrower per title who has Clean Code? Ravi (Asha has one too) A Loan per copy
map.get(title) for a missing title, then unboxing java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.Map.get(Object)" is null getOrDefault, or return an empty list
Searching a field with no index java.lang.NullPointerException: Cannot invoke "java.util.Map.getOrDefault(Object, Object)" because the return value of "java.util.Map.get(Object)" is null (we tried search("isbn", ...) while only title, author and subject were indexed) Check the field, or index.getOrDefault(field, Map.of())
Lending to a blocked member (no error, the member keeps borrowing) Check status first: IllegalStateException: Asha is BLOCKED
Fine rule inside giveBack() every rule change edits the desk A FinePolicy strategy
Returned copy straight back on the shelf anyone can take a reserved copy ON_HOLD for the first in the queue

Mini project: a complete library

One program with everything: word-level search, lending with limits, fines, blocking and paying, a holds queue, hold expiry after 3 days, and SMS notifications.

import java.time.*;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.function.Consumer;

enum ItemStatus { AVAILABLE, LOANED, ON_HOLD, LOST }
enum AccountStatus { ACTIVE, BLOCKED }

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

class BookItem {
    final String barcode; final Book book;
    ItemStatus status = ItemStatus.AVAILABLE; Member heldFor; LocalDate holdUntil;
    BookItem(String barcode, Book book) { this.barcode = barcode; this.book = book; }
    public String toString() { return barcode + " " + status; }
}

class Member {
    final String id, name; int fineDue; AccountStatus status = AccountStatus.ACTIVE;
    final List<Loan> loans = new ArrayList<>();
    Member(String id, String name) { this.id = id; this.name = name; }
}

record Loan(BookItem item, Member member, LocalDate issued, LocalDate due) {}

interface FinePolicy { int fine(long daysLate); }

class Catalog {
    private final Map<String, Map<String, List<Book>>> index = new HashMap<>();
    private final Map<String, List<BookItem>> copies = new HashMap<>();
    void add(Book b, String... barcodes) {
        for (String[] f : new String[][]{{"title", b.title()}, {"author", b.author()}, {"subject", b.subject()}})
            for (String word : f[1].toLowerCase().split(" "))          // index every word
                index.computeIfAbsent(f[0], k -> new HashMap<>()).computeIfAbsent(word, k -> new ArrayList<>()).add(b);
        for (String c : barcodes) copies.computeIfAbsent(b.isbn(), k -> new ArrayList<>()).add(new BookItem(c, b));
    }
    List<Book> search(String field, String word) {
        return index.getOrDefault(field, Map.of()).getOrDefault(word.toLowerCase(), List.of());
    }
    List<BookItem> copiesOf(Book b) { return copies.getOrDefault(b.isbn(), List.of()); }
}

class Library {
    static final int MAX_BOOKS = 2, LOAN_DAYS = 14, BLOCK_AT = 50, HOLD_DAYS = 3;
    final Catalog catalog = new Catalog();
    final FinePolicy finePolicy;
    final Map<String, Deque<Member>> holds = new HashMap<>();     // isbn -> FIFO queue
    final List<Consumer<String>> listeners = new ArrayList<>();
    Library(FinePolicy p) { finePolicy = p; }

    private void notifyAll(String msg) { listeners.forEach(l -> l.accept(msg)); }

    String borrow(Book b, Member m, LocalDate today) {
        if (m.status == AccountStatus.BLOCKED) return m.name + ": BLOCKED, fine due " + m.fineDue;
        if (m.loans.size() >= MAX_BOOKS) return m.name + ": limit of " + MAX_BOOKS + " books reached";
        expireHolds(b, today);
        for (BookItem c : catalog.copiesOf(b)) {
            boolean free = c.status == ItemStatus.AVAILABLE;
            boolean mine = c.status == ItemStatus.ON_HOLD && c.heldFor == m;
            if (free || mine) {
                c.status = ItemStatus.LOANED; c.heldFor = null;
                Loan l = new Loan(c, m, today, today.plusDays(LOAN_DAYS)); m.loans.add(l);
                return m.name + " borrowed " + c.barcode + ", due " + l.due();
            }
        }
        Deque<Member> q = holds.computeIfAbsent(b.isbn(), k -> new ArrayDeque<>());
        if (!q.contains(m)) q.addLast(m);
        return m.name + ": no copy free, hold position " + (new ArrayList<>(q).indexOf(m) + 1);
    }

    void giveBack(Loan l, LocalDate today) {
        int fine = finePolicy.fine(ChronoUnit.DAYS.between(l.due(), today));
        Member m = l.member(); m.loans.remove(l); m.fineDue += fine;
        if (m.fineDue >= BLOCK_AT) m.status = AccountStatus.BLOCKED;
        System.out.println(m.name + " returned " + l.item().barcode + " on " + today + ", fine " + fine);
        handOver(l.item(), today);
    }

    private void handOver(BookItem c, LocalDate today) {
        Deque<Member> q = holds.getOrDefault(c.book.isbn(), new ArrayDeque<>());
        Member next = q.pollFirst();
        if (next == null) { c.status = ItemStatus.AVAILABLE; return; }
        c.status = ItemStatus.ON_HOLD; c.heldFor = next; c.holdUntil = today.plusDays(HOLD_DAYS);
        notifyAll(next.name + ": " + c.book.title() + " (" + c.barcode + ") is ready until " + c.holdUntil);
    }

    private void expireHolds(Book b, LocalDate today) {
        for (BookItem c : catalog.copiesOf(b))
            if (c.status == ItemStatus.ON_HOLD && today.isAfter(c.holdUntil)) {
                System.out.println("hold for " + c.heldFor.name + " on " + c.barcode + " expired");
                handOver(c, today);
            }
    }

    void pay(Member m, int amount) {
        m.fineDue = Math.max(0, m.fineDue - amount);
        if (m.fineDue < BLOCK_AT) m.status = AccountStatus.ACTIVE;
        System.out.println(m.name + " paid " + amount + ", owes " + m.fineDue + ", " + m.status);
    }
}

public class Main {
    public static void main(String[] args) {
        Library lib = new Library(days -> (int) Math.max(0, days) * 5);
        lib.listeners.add(msg -> System.out.println("  SMS -> " + msg));
        Book cc = new Book("ISBN-1", "Clean Code", "Robert Martin", "Programming");
        Book wf = new Book("ISBN-2", "Wings of Fire", "A P J Abdul Kalam", "Biography");
        lib.catalog.add(cc, "B-101");
        lib.catalog.add(wf, "B-201", "B-202");
        Member asha = new Member("M1", "Asha"), ravi = new Member("M2", "Ravi"), neha = new Member("M3", "Neha");

        System.out.println("search title 'code': " + lib.catalog.search("title", "code").get(0).title());
        System.out.println("search author 'kalam': " + lib.catalog.search("author", "kalam").get(0).title());
        LocalDate d = LocalDate.of(2026, 11, 2);
        System.out.println(lib.borrow(cc, asha, d));
        System.out.println(lib.borrow(cc, ravi, d));
        System.out.println(lib.borrow(cc, neha, d));
        lib.giveBack(asha.loans.get(0), LocalDate.of(2026, 11, 20));     // 4 days late
        System.out.println(lib.borrow(cc, neha, LocalDate.of(2026, 11, 21)));  // not her turn
        System.out.println(lib.borrow(cc, ravi, LocalDate.of(2026, 11, 25)));  // too late: hold expired
        System.out.println(lib.borrow(cc, neha, LocalDate.of(2026, 11, 25)));
        System.out.println(lib.borrow(wf, asha, LocalDate.of(2026, 11, 25)));
        lib.giveBack(asha.loans.get(0), LocalDate.of(2026, 12, 20));     // 11 days late
        System.out.println(lib.borrow(wf, asha, LocalDate.of(2026, 12, 20)));
        lib.pay(asha, 75);
        System.out.println(lib.borrow(wf, asha, LocalDate.of(2026, 12, 20)));
    }
}

Real output:

search title 'code': Clean Code
search author 'kalam': Wings of Fire
Asha borrowed B-101, due 2026-11-16
Ravi: no copy free, hold position 1
Neha: no copy free, hold position 2
Asha returned B-101 on 2026-11-20, fine 20
  SMS -> Ravi: Clean Code (B-101) is ready until 2026-11-23
Neha: no copy free, hold position 1
hold for Ravi on B-101 expired
  SMS -> Neha: Clean Code (B-101) is ready until 2026-11-28
Ravi: no copy free, hold position 1
Neha borrowed B-101, due 2026-12-09
Asha borrowed B-201, due 2026-12-09
Asha returned B-201 on 2026-12-20, fine 55
Asha: BLOCKED, fine due 75
Asha paid 75, owes 0, ACTIVE
Asha borrowed B-201, due 2027-01-03

What happened:

  • Searching the word "code" in titles and "kalam" in authors works, because every word is indexed.
  • Asha returned B-101 4 days late (due 16 Nov, back 20 Nov): fine 20. The copy went ON_HOLD for Ravi until 23 November.
  • Neha tried on the 21st: not her turn.
  • Ravi came on the 25th, after his hold ended, so the hold expired, the copy moved to Neha (she was notified), and Ravi was put back in the queue.
  • Asha returned Wings of Fire 11 days late: 55 more, 75 in total, so she was BLOCKED until she paid.

Practice

1. Add renew(Loan): extend the due date by 14 days, but only if nobody is waiting for that title.

Answer

Look up the title's holds queue. If it's empty, replace the loan with a new Loan(item, member, issued, due.plusDays(14)) (records are immutable, so you make a new one). If someone is waiting, refuse with an IllegalStateException("someone is waiting for " + title). Also keep a renewal count and allow, say, at most 2.

2. Add a LOST status.

Answer

Add LOST to ItemStatus (the mini project has it). markLost(Loan l, int price): set the item's status to LOST, remove the loan from the member, and add price to fineDue (which may block them). Lost copies are skipped by borrow because they are not AVAILABLE.

3. Students pay 2 rupees a day, staff pay nothing. How do you add this without editing giveBack?

Answer

Give each member a FinePolicy (or pick one from a map by member type): Map.of(STUDENT, days -> max(0, days) * 2, STAFF, days -> 0). giveBack asks the member's policy. That's the Strategy pattern: new rules are new policies, not new ifs.

4. Why does borrow check "on hold for this member", not just "on hold"?

Answer

An ON_HOLD copy is kept for one person. If borrow only skipped ON_HOLD copies, the person it's held for could never collect it; if it allowed any ON_HOLD copy, Neha could take Ravi's. So: free copies for anyone, held copies only for the member they're held for.

5. Why is Book a record but BookItem a normal class?

Answer

A Book's data never changes after it's catalogued, so an immutable record fits. A BookItem's status changes all the time (AVAILABLE → LOANED → ON_HOLD), so it needs a mutable field.

Quick quiz

A loan is 14 days, the fine is 5 rupees a day, and a member is blocked at 50. A book is borrowed on 1 November and returned on 20 November. What is the fine, and is the member blocked? (a) 0, active (b) 25, active (c) 30, active (d) 95, blocked

Answer

(b) 25, active. Due date: 1 November + 14 days = 15 November. Returned 20 November: 5 days late. 5 × 5 = 25, which is under 50, so the member stays ACTIVE.

Interview questions

  1. What is the difference between Book and BookItem? Book is the title (one per ISBN); BookItem is a physical copy with a barcode and a status. Search uses Books; lending uses BookItems.
  2. What are the main classes? Book, BookItem, Catalog, Member, Librarian (or LendingService), Loan, Reservation/holds queue, FinePolicy, Notifier.
  3. How do you search fast? An index (map) per field: field → word → books, built when a book is added.
  4. Where do fines live? In a FinePolicy strategy, called on return; the result is added to the member's account.
  5. How do you block members? An account status checked at the start of every lend.
  6. How do reservations work? A FIFO queue per title; a returned copy becomes ON_HOLD for the first member, who is notified and has a few days to collect.
  7. Which patterns did you use? Strategy (fines), Observer (notifications), and arguably Factory for creating copies.
  8. How do you stop two librarians lending the same copy? Make check-and-take atomic: a lock on the copy or a compare-and-set on its status (or a database row lock).
  9. How would you store this? Tables for books, book_items (with status), members, loans (with due and returned dates), holds (with position and expiry).
  10. What would you test? Fines on the due date and one day after, the borrow limit, blocking and unblocking, hold order, hold expiry.

Glossary

Term Meaning, with an example
Library management system Software that tracks a library's books, members, loans, fines and reservations
Requirement Something the system must do, agreed before coding: "lend a copy for 14 days"
Machine-coding round An interview round where you design and code a working system in 60-90 minutes
Member A person who borrows books: Asha
Librarian The desk that lends and takes back books; the class holding the lending rules
Catalog The searchable list of every book the library owns
Book The title: Book("ISBN-1", "Clean Code", "Robert Martin", "Programming")
BookItem One physical copy with its own barcode and status: B-101 AVAILABLE
ISBN International Standard Book Number, printed on the back of a book; ours are made up
Barcode The id sticker on a copy that a scanner reads: B-101
ItemStatus AVAILABLE, LOANED, ON_HOLD (and LOST in the mini project)
Index A lookup table from a word to where it appears: "programming" → [Clean Code]
Search by title / author / subject Looking up the matching index
Record A class that only holds values; Java writes equals, hashCode, toString
Enum A fixed list of named values: enum AccountStatus { ACTIVE, BLOCKED }
Lending Giving a copy to a member and recording a Loan
Loan Which copy, which member, and the due date
Return Taking a copy back, freeing it and working out the fine
Due date The day a copy must be back: borrow date + 14 days
Fine Money for returning late: days late × 5 rupees
FinePolicy Our interface for the fine rule; a Strategy
Strategy pattern Put a changeable rule behind an interface and swap implementations
Account status Whether a member may borrow: ACTIVE or BLOCKED
LocalDate A Java date with no time: LocalDate.of(2026, 11, 2)
ChronoUnit.DAYS.between Days from one date to another
IllegalStateException Thrown when an object's current state forbids an action
NullPointerException Thrown when you use a null as if it were an object
getOrDefault Map lookup that returns a default instead of null
Reservation A request for the next free copy of a title
Hold A returned copy kept aside for one member: ON_HOLD
Holds queue The FIFO list of members waiting for a title
FIFO First in, first out: the first to reserve is served first
Hold expiry A hold ends if not collected in time (3 days in the mini project)
Notification on availability Telling a member their reserved book is ready
Observer pattern A subject keeps listeners and calls them when something happens
Listener Code that reacts to an event: msg -> System.out.println("SMS -> " + msg)
Consumer Java's functional interface for "takes a value, returns nothing"
Lambda A short inline function: days -> days * 5

Summary

  • A count per title lost who had which copy and counted 3 copies of a 2-copy book.
  • Book (the title) and BookItem (a physical copy with a barcode and status) fixed it; the Catalog indexes books by title, author and subject.
  • The Librarian lends with due dates, checks limits and account status, and charges fines through a FinePolicy strategy.
  • When all copies are out, a FIFO holds queue keeps the next copy ON_HOLD for the first member, and Observer listeners notify them.
  • Next episode: design BookMyShow, part 1: cinemas, screens, shows, a seat map and the booking flow.