Courses / Machine Coding and Low-Level Design in TypeScript / Chapter 9
Module 4 · Design problems I: parking, elevators and libraries · Chapter 9 of 28
Library Management: Catalogue, Copies, Loans, Holds and Fines
Builds on Solving a Design Problem: Requirements to Tested Code in Six Steps and Design Patterns in TypeScript: Creational, Structural and Behavioural. Next up: Parcel Locker Service: Slots, Pickup Codes and Expiry.
Part 1 · Requirements
Titles, copies and members
A city library lends the same book to many people, one physical copy at a time, and it has to remember who has what and when it is due back. This chapter models a Chennai city library so that those rules are classes you can run and test.
The first idea is a distinction that the rest of the design leans on. A title is a book as a work: its name and author, the thing people search for. A copy is one physical item of that title, with a barcode, that can be on a shelf, in someone's bag or lost. The library may own three copies of one title and one copy of another. Searching finds titles. Lending moves copies.
A member is a person with a library card. A loan records that a member has a copy until a due date. A hold is a request to be first in line for a title that has no copy in. These words will become the classes. The functional requirements, in our model, are these.
- Members search the catalogue by words in the title and by author.
- A member can borrow an available copy of a title. Each loan lasts 14 days.
- A member can have at most three loans at once.
- Returning a copy late costs ₹2 for each started day.
- A member with an unpaid fine cannot borrow until it is paid.
- If every copy of a title is out, a member can place a hold. The first member in the queue gets the next returned copy, kept on a hold shelf for three days.
- The member is told when the copy is ready. If they do not collect it in time, it goes to the next member in the queue.
The loan period, the limit and the fine are made up for this chapter. A real library would set its own.
Write the rules as short sentences with a number in them, because a number can be tested. "Members may borrow a few books" cannot be checked, while "at most three loans at once" can. Each sentence above will turn into at least one test before the chapter ends.
Questions, scope and quality
Most of these rules answer questions that a prompt like "design a library system" leaves open. Ask the ones whose answer adds or removes a class.
| Question | If the answer is yes | Our answer |
|---|---|---|
| Does the library own several copies of one book? | Separate classes for the work and the physical item | Yes |
| Can a member queue for a book that is out? | A hold queue per title, and a hold shelf | Yes |
| Are fines charged for late returns? | A fine policy and an owed amount per member | Yes |
| Are there several branches? | Copies get a branch, and transfers between branches | No, sketched at the end |
| Is search by subject or full text? | A search engine instead of simple indexes | No, title words and author |
Money is held as integer paise, so a fine of ₹2 is 200 and ₹4.00 is 400. A rupee value is formatted only when it is shown.
Scope is a design tool here, not only a list of exclusions. Leaving branches out of the first version means the copy has no branch field yet, and that keeps every early test shorter.
Three non-functional needs shape the design. Search must stay quick as the catalogue grows, so we build indexes (lookup tables from a word or an author to the titles that contain it) when a title is added, instead of scanning every title for every search. Time must be injectable, because due dates and fines depend on days passing and a test cannot wait. And a rule that is broken must say which rule: every refusal has a code.
Check yourself
Why keep titles and copies as separate things?
- People search for and place holds on a title, while lending, returning and losing happen to one physical copy.
- One title can have many copies, each in a different state.
How much is a fine for a book returned 2 days and 3 hours late, in paise?
- 600 paise: three started days at 200 paise each.
Why build search indexes when a title is added?
- A search then reads a few sets instead of scanning every title, and the cost of building them is paid once per title.
Part 2 · Use cases
Who does what
An actor is a role outside the system with a goal it serves, and a use case is one such goal. There are two actors. The member searches, places holds, collects them and borrows. The librarian works the desk: checking in returned copies and recording fine payments. Returns belong to the librarian because a copy can come back through a drop box with nobody present, which is why giveBack in the code takes only a copy id and finds the member from the loan.
The drawing follows the earlier cases: actors are blue boxes, use cases are pills, and an arrow from a base case is labelled "includes" or "extended by" (the UML chapter explains why the extend arrow is drawn from the base case here). Borrowing and collecting a hold both include a check of the member's limit and fines: every borrow runs it. Applying a fine and notifying the next hold extend a return. They are extra steps that happen only sometimes: only when the copy came back late, and only when someone is waiting.
A secondary actor would be something outside the system that the system calls, such as an SMS gateway. We treat the notification as an event with listeners instead, so no outside actor appears yet. When a real sender exists, it joins the diagram as an actor on the right-hand side, called by the service rather than calling it.
Flows and alternatives
| Use case | Main flow | Alternatives |
|---|---|---|
| Search | Member types words; titles containing every word are listed | No match: empty list |
| Borrow | Member picks a title; a free copy is lent; due date set | Limit reached, fines due, no copy free |
| Check in a return | Librarian scans the copy; any fine is added to the member's account | Copy not on loan: refused. Hold waiting: copy goes to the hold shelf |
| Place a hold | Member joins the queue for a title with no copy in | A copy is available: borrow instead. Already queued: refused |
| Collect a hold | The member at the front of the queue takes the reserved copy | Another member asks for it: refused |
| Record a payment | Librarian records what the member paid; the owed amount drops, never below zero | None |
Alternatives need decisions, and most of them are one line. A search with no match returns an empty list, not an error, because an empty result is a normal answer. A return of a copy that is not on loan is an error, because it points to a data problem, perhaps a scanner mistake. A borrow with fines due is refused with its own code, so that a screen can tell the member to pay first.
Note the rule for placing a hold. If a copy is free, a hold would be pointless and would make the member wait behind nobody, so the service refuses it with the code AVAILABLE_NOW.
Use cases as test names
The use cases become test.todo names that exist before any code does.
test.todo('member searches the catalogue by title words'); test.todo('member borrows a copy and gets a due date'); test.todo('member places a hold on a title with no copy in'); test.todo('member collects a copy from the hold shelf'); test.todo('librarian checks in a late copy, fine added'); test.todo('librarian records a fine payment');
✔ member searches the catalogue by title words (0.526ms) # TODO ✔ member borrows a copy and gets a due date (0.0719ms) # TODO ✔ member places a hold on a title with no copy in (0.056ms) # TODO ✔ member collects a copy from the hold shelf (0.0451ms) # TODO ✔ librarian checks in a late copy, fine added (0.0591ms) # TODO ✔ librarian records a fine payment (0.0584ms) # TODO ℹ tests 6 ℹ todo 6
Output (durations vary)
A useful habit is to write each name as a sentence a librarian could confirm. If the librarian reads "librarian checks in a late copy, fine added" and nods, the name is doing its job. If they ask "and when it is on time?", the name has found an alternative that needs its own test.
Six names, reported as todos with no failures. The riskiest ones, borrow and hold, will get several tests each, and each todo becomes a real test once the service exists.
Why does "apply a fine" extend "check in a return" instead of being included?
- A fine applies only when the copy is late; an included case would run on every return.
A copy comes back through the drop box at night. Which actor starts that use case, and what does the code need to know?
- The librarian, who checks it in the next morning; the member is not there.
- Only the copy id: the open loan for that copy names the member and the due date, which is why giveBack takes a copy id alone.
Part 3 · Class diagram
From nouns to classes
Underline the nouns in the requirements: catalogue, title, copy, member, loan, hold, fine, notification. Not all of them need a class.
| Noun | Decision | Why |
|---|---|---|
| Catalogue | Class Catalogue | Owns titles and copies and their indexes |
| Title | Value Title: id, name, author | Describes a work; never changes |
| Copy | Class Copy | Has a lifecycle with rules |
| Member | Class Member | Holds a loan count and an owed amount |
| Loan | Value Loan: copy, member, due date | A record of a fact |
| Hold | A queue of member ids per title, HoldQueue | Order is all that matters |
| Fine | Class FinePolicy | A rule that may change |
| Notification | Events and listeners | Sent by the service, handled elsewhere |
Other designs often call these two classes Book and BookItem; the names matter less than the split. A Member here keeps only a count of loans, not a list, because the limit check needs the count and the loans themselves live in the service, keyed by copy id. A list on the member would be a second copy of the same facts, and the two could drift apart.
The class diagram
borrow(memberId, titleId)giveBack(copyId): PaiseplaceHold, collectsweepShelf()search(words): Title[]byAuthor(name)copiesOf(titleId)id, name, authorid, titleIdstate: CopyStateapply(event)id, nameloans: numberowed: PaisecopyId, memberIddueAtqueue of member ids per titlefine(dueAt, returnedAt): Paiseon(listener)emit(event)- LoanService 1 → 1 Catalogue
- Catalogue 1 → * Title (value)
- Title (value) 1 → 1..* Copy
- Member 1 → 0..3 Loan (value)
- Loan (value) 0..1 → 1 Copy
- LoanService 1 → 1 HoldQueue
- LoanService 1 → 1 FinePolicy
- LoanService 1 → 1 Events
A catalogue has many titles and a title has one or more copies. A member has at most three loans, shown as 0..3, and each loan points at one copy. LoanService ties the pieces together and owns the queue, the fine policy and the events object.
Read the rest of the diagram as sentences. A catalogue holds many titles. A title has one or more copies in stock; the code lets a title be added before its copies. A member has up to three loans. A loan refers to exactly one copy, and a copy is in at most one open loan at a time. FinePolicy and HoldQueue have a single owner, the loan service.
The skeleton in TypeScript
The shared types come first: the money type, the Title value and the error codes.
export type Paise = number; export interface Title { readonly id: string; readonly name: string; readonly author: string; } export type LibraryCode = | 'UNKNOWN_ID' | 'NOT_AVAILABLE' | 'AVAILABLE_NOW' | 'NOT_ON_LOAN' | 'LIMIT_REACHED' | 'FINES_DUE' | 'DUPLICATE_HOLD' | 'HELD_FOR_OTHER' | 'BAD_STATE'; export class LibraryError extends Error { readonly code: LibraryCode; constructor(code: LibraryCode, message: string) { super(message); this.name = 'LibraryError'; this.code = code; } }
Title is an object type with three fields, so tests build titles with plain object literals. Paise is only a name for number, which makes signatures easier to read: a function that returns Paise is clearly returning money.
All errors are LibraryError with a code from a closed union. Tests assert on the code. The next check type-checks the whole project.
npx tsc -p .
(no output, exit code 0)Output
Why is Loan a value and not a class with methods?
- It only records a fact, which copy a member has until when; the rules live in the service and the copy.
What does the observer pattern buy the loan service here?
- The service announces that a hold is ready without knowing how members are told, so notification channels can change freely.
Part 4 · Copy lifecycle and the return sequence
States of a copy
A copy is available, on loan, on the hold shelf or lost. Each move has an event name: lend, give back, reserve, collect, release and lose. A state machine lists these moves in a table, and anything not in the table is refused.
Watch for the copy refusing to be lent while it waits on the hold shelf
Read it as steps
A copy reserved for one member cannot be lent to anyone else.
The refused move is the one that protects the queue. A copy on the hold shelf is reserved for one member. If anyone tries to lend it, the table has no lend entry for that state, so the call fails with HELD_FOR_OTHER. The service never has to ask whether a copy is reserved; the copy's own state says so. Through the service the same situation shows up in two ways. borrow only picks a copy that is available, so a title whose only copy is on the shelf is refused with NOT_AVAILABLE. collect by a member the shelf is not held for gets HELD_FOR_OTHER.
export type CopyState = 'available' | 'on-loan' | 'hold-shelf' | 'lost'; export type CopyEvent = | 'lend' | 'giveBack' | 'reserve' | 'collect' | 'release' | 'lose'; type Moves = Partial<Record<CopyEvent, CopyState>>; const NEXT: Record<CopyState, Moves> = { available: { lend: 'on-loan' }, 'on-loan': { giveBack: 'available', reserve: 'hold-shelf', lose: 'lost', }, 'hold-shelf': { collect: 'on-loan', release: 'available' }, lost: {}, };
What a return does
A return is the busiest operation in the library, and it is where the use cases meet. The service finds the loan, works out the fine and adds it to the member's account, closes the loan, and then decides where the copy goes. If someone is waiting in the hold queue, the copy is reserved and the first member is notified. Otherwise it simply becomes available.
Watch for the copy going to the hold shelf instead of back to the stacks
Read it as steps
Returning the copy reserves it for the first member in the queue and tells them.
The code is two short methods. giveBack does the bookkeeping.
giveBack(copyId: string): Paise {
const loan = this.#loans.get(copyId);
if (!loan) throw new LibraryError('NOT_ON_LOAN', copyId);
const copy = this.#d.catalogue.copy(copyId);
const m = this.member(loan.memberId);
const fine = this.#d.fines.fine(loan.dueAt, this.#d.clock.now());
m.owed += fine;
m.loans -= 1;
this.#loans.delete(copyId);
this.#shelveOrRelease(copy);
return fine;
}#shelveOrRelease makes the decision about the copy.
#shelveOrRelease(copy: Copy): void { if (this.#holds.waiting(copy.titleId) === 0) { copy.apply('giveBack'); return; } copy.apply('reserve'); this.#assign(copy); } // Put the copy on the shelf for the first member in the queue. #assign(copy: Copy): void { const memberId = this.#holds.shift(copy.titleId)!; const days = this.#d.policy.holdDays; const until = this.#d.clock.now() + days * DAY; this.#shelf.set(copy.id, { memberId, until }); const titleId = copy.titleId; this.#d.events.emit({ type: 'hold-ready', memberId, titleId }); }
Run the driver
This is the driver for the chapter. It borrows, fails to borrow a second time, places a hold, returns late and collects. The set-up, with two titles, three copies and three members, is shown in the code lessons.
const { clock, catalogue, events, svc } = build(); events.on((e) => console.log(`notify ${e.memberId}: ${e.type}`)); const loan = svc.borrow('M1', 'T1'); const due = loan.dueAt / DAY; console.log(`Isha borrowed ${loan.copyId}, due day ${due}`); try { svc.borrow('M2', 'T1'); } catch (e) { console.log(`Kabir: ${(e as { code: string }).code}`); } const place = svc.placeHold('M2', 'T1'); console.log(`Kabir is number ${place} in the queue`); clock.advanceMinutes(16 * DAY_MIN); const fine = svc.giveBack('C1'); console.log(`returned 2 days late, fine ${rupees(fine)}`); console.log(`C1 is ${catalogue.copy('C1').state}`); svc.collect('M2', 'T1'); console.log(`C1 is ${catalogue.copy('C1').state}`);
Isha borrowed C1, due day 14 Kabir: NOT_AVAILABLE Kabir is number 1 in the queue notify M2: hold-ready returned 2 days late, fine ₹4.00 C1 is hold-shelf C1 is on-loan
Output
Read the output top to bottom as a story. A member borrows, a second member is refused and queues, time passes, the copy is returned and reserved, and the second member collects it. Every line is a use case from the earlier lesson.
Kabir's refused borrow comes out as NOT_AVAILABLE, which is why he placed a hold. When Isha returns the copy on day 16, 2 days after the due date of day 14, the fine is ₹4.00. The notify line is printed by a listener the driver registered. It appears before the return line because the event is sent inside giveBack, before the amount is returned. The copy ends on the hold shelf and then on loan once Kabir collects it.
Why does lending a copy on the hold shelf fail inside the copy, not in the service?
- The copy's state table has no lend entry for that state, so the rule holds wherever lend is called from.
In the driver, why does the notify line come before the fine line?
- The hold-ready event is emitted inside giveBack, before giveBack returns the fine to the caller.
Part 5 · Code: catalogue and loans
Indexes for search
A search for "salt road" should not read every title. When a title is added, the catalogue splits its name into lower-case words and records the title id under each word in a Map<string, Set<string>>. The same is done for the author. A search reads the set for each word and keeps the ids that are in all of them.
export class Catalogue { readonly #titles = new Map<string, Title>(); readonly #copies = new Map<string, Copy>(); readonly #byTitle = new Map<string, Copy[]>(); readonly #byWord = new Map<string, Set<string>>(); readonly #byAuthor = new Map<string, Set<string>>(); addTitle(t: Title): void { this.#titles.set(t.id, t); this.#byTitle.set(t.id, []); for (const w of words(t.name)) this.#index(this.#byWord, w, t.id); this.#index(this.#byAuthor, t.author.toLowerCase(), t.id); } addCopy(copyId: string, titleId: string): Copy { if (!this.#titles.has(titleId)) { throw new LibraryError('UNKNOWN_ID', titleId); } const copy = new Copy(copyId, titleId); this.#copies.set(copyId, copy); this.#byTitle.get(titleId)!.push(copy); return copy; } #index(map: Map<string, Set<string>>, key: string, id: string): void { const set = map.get(key) ?? new Set<string>(); set.add(id); map.set(key, set); }
The two maps answer different questions. byWord maps each word to the titles whose name contains it, and byAuthor maps a whole lower-cased author name to their titles. Both are built inside addTitle, so adding a title keeps them in step without any other class remembering to do it.
#index is the small helper that adds an id to the set for a key. A Set rather than an array means a title is stored once under a word even if the word appears twice in its name.
// Every word must appear in the title: intersect the word sets. search(query: string): Title[] { const sets = words(query).map((w) => this.#byWord.get(w)); if (sets.length === 0 || sets.includes(undefined)) return []; const [first, ...rest] = sets as Set<string>[]; const all = (id: string) => rest.every((s) => s.has(id)); const ids = [...first!].filter(all); return ids.map((id) => this.#titles.get(id)!); } byAuthor(author: string): Title[] { const ids = this.#byAuthor.get(author.toLowerCase()) ?? new Set(); return [...ids].map((id) => this.#titles.get(id)!); } copy(id: string): Copy { const c = this.#copies.get(id); if (!c) throw new LibraryError('UNKNOWN_ID', id); return c; } copiesOf(titleId: string): readonly Copy[] { return this.#byTitle.get(titleId) ?? []; } title(id: string): Title { const t = this.#titles.get(id); if (!t) throw new LibraryError('UNKNOWN_ID', id); return t; }
Limits and due dates
The loan service takes its collaborators in the constructor: the catalogue, a clock, the loan policy, the fine policy and the events object. Nothing in it calls Date.now(). Tests pass a FakeClock that moves forward by a number of minutes, and DAY_MIN (1,440) turns days into minutes. A small build() function in setup.ts creates the same library for every test and for the driver.
export function build() { const clock = new FakeClock(); const catalogue = new Catalogue(); const maps = { id: 'T1', name: 'Monsoon Maps', author: 'Asha Rao' }; const road = { id: 'T2', name: 'The Salt Road', author: 'Dev Menon' }; catalogue.addTitle(maps); catalogue.addTitle(road); catalogue.addCopy('C1', 'T1'); catalogue.addCopy('C2', 'T2'); catalogue.addCopy('C3', 'T2'); const events = new Events(); const svc = new LoanService({ catalogue, clock, events, policy: { loanDays: 14, maxLoans: 3, holdDays: 3 }, fines: new FinePolicy(200), }); svc.join('M1', 'Isha'); svc.join('M2', 'Kabir'); svc.join('M3', 'Tara'); return { clock, catalogue, events, svc }; }
export class FakeClock implements Clock { #t: number; constructor(start = 0) { this.#t = start; } now(): number { return this.#t; } advanceMinutes(minutes: number): void { this.#t += minutes * 60_000; } }
borrow first runs the member checks, then looks for an available copy, then lends it. The limit and the fines are checked before availability, so a member over the limit is told so even if no copy is free.
borrow(memberId: string, titleId: string): Loan {
const m = this.#canBorrow(memberId);
const copies = this.#d.catalogue.copiesOf(titleId);
const copy = copies.find((c) => c.state === 'available');
if (!copy) throw new LibraryError('NOT_AVAILABLE', titleId);
copy.apply('lend');
return this.#open(m, copy);
}
#canBorrow(memberId: string): Member {
const m = this.member(memberId);
if (m.owed > 0) throw new LibraryError('FINES_DUE', memberId);
if (m.loans >= this.#d.policy.maxLoans) {
throw new LibraryError('LIMIT_REACHED', memberId);
}
return m;
}
#open(m: Member, copy: Copy): Loan {
m.loans += 1;
const dueAt = this.#d.clock.now() + this.#d.policy.loanDays * DAY;
const loan = { copyId: copy.id, memberId: m.id, dueAt };
this.#loans.set(copy.id, loan);
return loan;
}
payFine(memberId: string, amount: Paise): void {
const m = this.member(memberId);
m.owed = Math.max(0, m.owed - amount);
}Fines and tests
Fines are a policy object, so the rule can change without touching the service.
export interface LoanPolicy { loanDays: number; maxLoans: number; holdDays: number; } export class FinePolicy { readonly #perDay: Paise; constructor(perDay: Paise) { this.#perDay = perDay; } // Each started day late costs the same; on time costs nothing. fine(dueAt: number, returnedAt: number): Paise { const late = returnedAt - dueAt; return late <= 0 ? 0 : Math.ceil(late / DAY) * this.#perDay; } }
Math.ceil(late / DAY) counts a started day as a full one, and a copy returned exactly on time costs nothing. The service adds the fine to the member's account in giveBack.
test('a loan is due after the loan period', () => { const { clock, svc } = build(); clock.advanceMinutes(3 * DAY_MIN); const loan = svc.borrow('M1', 'T2'); assert.equal(loan.dueAt, 17 * DAY); }); test('the fourth loan hits the limit', () => { const { svc } = build(); svc.borrow('M1', 'T1'); svc.borrow('M1', 'T2'); svc.borrow('M1', 'T2'); const limit = { code: 'LIMIT_REACHED' }; assert.throws(() => svc.borrow('M1', 'T2'), limit); });
The next test shows that a return frees a loan slot.
test('returning frees a slot under the limit', () => { const { svc } = build(); svc.borrow('M1', 'T1'); svc.borrow('M1', 'T2'); svc.borrow('M1', 'T2'); svc.giveBack('C1'); assert.equal(svc.borrow('M1', 'T1').copyId, 'C1'); }); test('when every copy is out the borrow is refused', () => { const { svc } = build(); svc.borrow('M1', 'T2'); svc.borrow('M2', 'T2'); const out = { code: 'NOT_AVAILABLE' }; assert.throws(() => svc.borrow('M3', 'T2'), out); });
test('fines count each started day late', () => { const { clock, svc } = build(); svc.borrow('M1', 'T1'); clock.advanceMinutes(14 * DAY_MIN); assert.equal(svc.giveBack('C1'), 0); svc.borrow('M1', 'T1'); clock.advanceMinutes(14 * DAY_MIN); clock.advanceMinutes(60); assert.equal(svc.giveBack('C1'), 200); }); test('an unpaid fine blocks borrowing until it is paid', () => { const { clock, svc } = build(); svc.borrow('M1', 'T1'); clock.advanceMinutes(16 * DAY_MIN); assert.equal(svc.giveBack('C1'), 400); assert.throws(() => svc.borrow('M1', 'T2'), { code: 'FINES_DUE' }); svc.payFine('M1', 400); assert.equal(svc.borrow('M1', 'T2').memberId, 'M1'); }); test('returning a copy that is not on loan is refused', () => { const { svc } = build(); assert.throws(() => svc.giveBack('C1'), { code: 'NOT_ON_LOAN' }); });
Part 6 · Extensions and trade-offs
The hold queue and its notification
The hold queue is deliberately small: a queue of member ids for each title.
// First come, first served: one queue of member ids per title. export class HoldQueue { readonly #queues = new Map<string, string[]>(); has(titleId: string, memberId: string): boolean { return this.#queues.get(titleId)?.includes(memberId) ?? false; } add(titleId: string, memberId: string): number { const q = this.#queues.get(titleId) ?? []; q.push(memberId); this.#queues.set(titleId, q); return q.length; } // Removes and returns the member at the front, if anyone waits. shift(titleId: string): string | undefined { return this.#queues.get(titleId)?.shift(); } waiting(titleId: string): number { return this.#queues.get(titleId)?.length ?? 0; } }
add returns the position, which is what the member is told. shift takes the member at the front. The service uses both when it places a hold and when it assigns a returned copy. The rest of the hold logic is in the service.
placeHold(memberId: string, titleId: string): number {
this.member(memberId);
const copies = this.#d.catalogue.copiesOf(titleId);
if (copies.some((c) => c.state === 'available')) {
throw new LibraryError('AVAILABLE_NOW', titleId);
}
if (this.#holds.has(titleId, memberId)) {
throw new LibraryError('DUPLICATE_HOLD', titleId);
}
return this.#holds.add(titleId, memberId);
}
collect(memberId: string, titleId: string): Loan {
const m = this.#canBorrow(memberId);
const copies = this.#d.catalogue.copiesOf(titleId);
const shelf = this.#shelf;
const mine = (c: Copy) => shelf.get(c.id)?.memberId === memberId;
const copy = copies.find(mine);
if (!copy) throw new LibraryError('HELD_FOR_OTHER', titleId);
copy.apply('collect');
this.#shelf.delete(copy.id);
return this.#open(m, copy);
}A hold is refused when a copy is available or the member is already queued. collect finds the copy that is shelved for this member. Any other member gets HELD_FOR_OTHER.
The notification is the observer in action. The service sends an event, and the listeners decide what to do.
export type LibraryEvent = | { type: 'hold-ready'; memberId: string; titleId: string } | { type: 'hold-expired'; memberId: string; titleId: string }; export type Listener = (e: LibraryEvent) => void; export class Events { readonly #listeners: Listener[] = []; on(fn: Listener): void { this.#listeners.push(fn); } emit(e: LibraryEvent): void { for (const fn of this.#listeners) fn(e); } }
Expiry and the tests
A hold that nobody collects must not block the copy forever. sweepShelf runs once a day. For every shelved copy whose time is up, it sends a hold-expired event. If another member is waiting, the copy stays on the shelf for them. Otherwise it is released.
// Run daily: holds nobody collected go to the next in line. sweepShelf(): void { const now = this.#d.clock.now(); for (const [copyId, s] of [...this.#shelf]) { if (s.until > now) continue; const copy = this.#d.catalogue.copy(copyId); const { memberId } = s; const titleId = copy.titleId; this.#d.events.emit({ type: 'hold-expired', memberId, titleId }); this.#shelf.delete(copyId); if (this.#holds.waiting(titleId) > 0) this.#assign(copy); else copy.apply('release'); } }
test('a hold needs every copy to be out', () => { const { svc } = seen(); const now = { code: 'AVAILABLE_NOW' }; assert.throws(() => svc.placeHold('M2', 'T1'), now); }); test('holds are served first come, first served', () => { const { svc, log, catalogue } = seen(); svc.borrow('M1', 'T1'); assert.equal(svc.placeHold('M2', 'T1'), 1); assert.equal(svc.placeHold('M3', 'T1'), 2); const dup = { code: 'DUPLICATE_HOLD' }; assert.throws(() => svc.placeHold('M3', 'T1'), dup); svc.giveBack('C1'); assert.deepEqual(log, ['hold-ready M2']); assert.equal(catalogue.copy('C1').state, 'hold-shelf'); const other = { code: 'HELD_FOR_OTHER' }; assert.throws(() => svc.collect('M3', 'T1'), other); assert.equal(svc.collect('M2', 'T1').copyId, 'C1'); });
test('an uncollected hold passes to the next member', () => { const { svc, clock, log } = seen(); svc.borrow('M1', 'T1'); svc.placeHold('M2', 'T1'); svc.placeHold('M3', 'T1'); svc.giveBack('C1'); clock.advanceMinutes(3 * DAY_MIN); svc.sweepShelf(); assert.deepEqual(log, [ 'hold-ready M2', 'hold-expired M2', 'hold-ready M3', ]); assert.equal(svc.collect('M3', 'T1').memberId, 'M3'); }); test('with nobody waiting an expired hold frees the copy', () => { const { svc, clock, catalogue } = seen(); svc.borrow('M1', 'T1'); svc.placeHold('M2', 'T1'); svc.giveBack('C1'); clock.advanceMinutes(3 * DAY_MIN); svc.sweepShelf(); assert.equal(catalogue.copy('C1').state, 'available'); });
✔ a hold needs every copy to be out (1.094ms) ✔ holds are served first come, first served (0.6328ms) ✔ an uncollected hold passes to the next member (0.2107ms) ✔ with nobody waiting an expired hold frees the copy (0.1262ms) ℹ tests 4 ℹ pass 4 ℹ fail 0
Output (durations vary)
The tests use a helper, seen, that records every event as text. They show first come, first served, the refusal of a second member who tries to collect, and the hand-over after three days. The log in the third test reads hold-ready M2, hold-expired M2, hold-ready M3, which is the order a member would be told things.
Every use case, tested
The use case lesson left six test.todo names. Each one now becomes an acceptance test: it reaches one actor's goal through the service and the catalogue, built by the same build() as the driver, rather than testing one class alone.
test('member searches the catalogue by title words', () => { const { catalogue } = build(); const found = catalogue.search('monsoon'); assert.deepEqual(found.map((t) => t.id), ['T1']); }); test('member borrows a copy and gets a due date', () => { const { svc } = build(); const loan = svc.borrow('M1', 'T2'); assert.equal(loan.copyId, 'C2'); assert.equal(loan.dueAt, 14 * DAY); }); test('member places a hold on a title with no copy in', () => { const { svc } = build(); svc.borrow('M1', 'T1'); assert.equal(svc.placeHold('M2', 'T1'), 1); });
test('member collects a copy from the hold shelf', () => { const { svc } = build(); svc.borrow('M1', 'T1'); svc.placeHold('M2', 'T1'); svc.giveBack('C1'); assert.equal(svc.collect('M2', 'T1').copyId, 'C1'); }); test('librarian checks in a late copy, fine added', () => { const { svc, clock } = build(); svc.borrow('M3', 'T2'); clock.advanceMinutes(15 * DAY_MIN); assert.equal(svc.giveBack('C2'), 200); assert.equal(svc.member('M3').owed, 200); }); test('librarian records a fine payment', () => { const { svc, clock } = build(); svc.borrow('M3', 'T2'); clock.advanceMinutes(15 * DAY_MIN); svc.giveBack('C2'); svc.payFine('M3', 200); assert.equal(svc.member('M3').owed, 0); });
✔ member searches the catalogue by title words (1.6748ms) ✔ member borrows a copy and gets a due date (0.2323ms) ✔ member places a hold on a title with no copy in (0.2111ms) ✔ member collects a copy from the hold shelf (0.2627ms) ✔ librarian checks in a late copy, fine added (0.1379ms) ✔ librarian records a fine payment (0.1109ms) ℹ tests 6 ℹ pass 6 ℹ fail 0 ℹ todo 0
Output (durations vary)
The late check-in uses Tara, who borrows C2 and is checked in on day 15, one day after the due date, so she owes 200 paise until the payment is recorded. The whole suite now has 23 tests, all passing, with no todo left.
✔ an uncollected hold passes to the next member (0.2107ms) ℹ tests 23 ℹ pass 23 ℹ fail 0 ℹ todo 0
Output: whole suite
Branches, transfers and trade-offs
A library with several branches needs one more idea. A copy belongs to a branch, and a hold may be satisfied by a copy from another branch, which must travel. We would add a state in-transit to the copy table, a branchId to the copy, and a transfer step to the return flow. We did not build this, so treat it as a plan. The existing pieces would stay: the copy's table gets one row, and the hold queue and the observer do not change.
Every design leaves costs. The service keeps loans and the hold shelf in memory, so a restart loses them; a real library would put them behind a repository. A fine is added when the copy is returned, so a member who never returns a copy never owes anything, and a real library would add a rule for that.
The observer has one more cost, and a run shows it. Listeners run synchronously inside emit, so a slow listener slows the return. Here the first listener throws, during a return that has a hold waiting.
const { svc, events, catalogue } = build(); const seen: string[] = []; events.on(() => { throw new Error('boom'); }); events.on((e) => seen.push(e.type)); svc.borrow('M1', 'T1'); svc.placeHold('M2', 'T1'); try { svc.giveBack('C1'); } catch (e) { console.log(`giveBack threw ${(e as Error).message}`); } console.log(`C1 is ${catalogue.copy('C1').state}`); console.log(`second listener saw ${seen.length} events`); console.log(`Isha has ${svc.member('M1').loans} loans`);
giveBack threw boom C1 is hold-shelf second listener saw 0 events Isha has 0 loans
Output
The return itself happened: the loan is closed and the copy is on the hold shelf. But the desk saw an error, so a librarian would think the check-in failed, and the second listener never heard the event, so Kabir would not be told. That breaks the promise from the use case lesson that a failed notification must not block a return. The fix is to catch errors per listener inside emit, or to queue events and deliver them after the return completes.
Finally, the hold queue is per title, not per copy. That is deliberate: members care about the book, not the barcode.
| Term |
|---|
All chapters · Previous: Elevator System: Cars, Hall Calls and Dispatching