AlgoViz

Design a library management system

medium 85 min

Model a lending library: titles and copies, members with plans, loans, a waiting list and fines.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:58

Theory

Read or listen first. About 3 min.

What it is

A library management system in a low-level design round is the software behind the counter: what the library owns, who may borrow, who has what until when, who waits for it, and what a late day costs.

Underneath it is a lending system: things that go out and come back, with a limit for each person and a queue for each kind of thing. Cars, tools, costumes, meeting equipment and e-book licences have the same shape.

The answer is one coordinator with five verbs, two small owners (catalog and waiting list), a few records, and one interface for fines. Its centre is a method of eight lines that decides where a free copy goes.

Why it exists

It is asked because everybody knows libraries, and because the word book hides a modelling question that experience answers at once: is it the text or the thing in your hand?

It mixes three kinds of rules: numbers that change (limits), behaviour that changes (fines) and rules that must never break (one copy, one reader). Good designs treat the three differently.

It is also a small lesson in time. Due days, grace, expiry and reminders are all about days passing while no code runs. Much of the design is choosing what to store and what to calculate when asked.

A short history

  1. 1876

    Melvil Dewey publishes the decimal classification, first as a pamphlet of 44 pages: a key for where a book stands, not for which copy it is.

  2. 1960s

    The Library of Congress begins to use computers and devises the MARC format, so that catalog records can be read by machines.

  3. 1970

    The ISBN becomes an international standard. It numbers an edition. Copies need a number of their own.

  4. 1998

    The final report of FRBR describes four levels: work, expression, manifestation and item. Our title and copy are the last two.

  5. 2000

    Koha, made in New Zealand for the Horowhenua Library Trust, goes live in January. Its project calls it the first free library software.

  6. 2002

    NISO publishes the first version of NCIP, a protocol for circulation: how systems of different makers tell each other about loans.

  7. 2007

    From 1 January all ISBNs have 13 digits. Systems that had stored them as 10 characters found out.

Words to know

Title
The description of a book: one for each ISBN.
Copy or item
One physical thing, with a barcode.
Loan
One copy with one member until a day.
Hold
A wish for any copy of a title. Also called reservation or request.
Hold shelf
Where a kept copy waits for its person for some days.
Lapse
The days to fetch are over. The copy moves on.
Plan
What a member signed for: limit, days, renewals, fines.
Grace
Late days that cost nothing. Ask whether they are forgiven or only delayed.
Facade
One simple door in front of several parts, with the order of steps inside.
Outbox
Messages stored with the change they tell about, and sent later.
Invariant
A sentence that is true after every call, such as: nobody waits while a copy is on the shelf.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

How it works

Step through the idea, or press Play.

Step 1 of 3

A member borrows a copy. Rules of the member, rules of the copy, then three writes in one step

Understand it

Start here

One card for each toy

A van lends toys in a village. It has two boats and one drum. There is no card for "boat". There is a card for each boat, and a card is always in exactly one place: under the toy, in a child's pocket on the board, or in the basket. Watch where the cards are.

The toy van, one card per toy
TOY VANWHO HAS ITSamAshaNoorWaiting: -KEPT: -D1B2B1

Two kinds of things, one card for each copy, three places a card can be. A library is this van with more shelves.

What an interviewer looks for here

  • Title and copy

    Is there a difference between Dracula and the Dracula with barcode D1? Everything else hangs on it.

  • The loan as an object

    Not a field in the book and a list in the member. One record that both sides read.

  • Rules that change

    Days, limits, fines. Which are numbers and which are behaviour?

  • What happens on return

    A returned copy may already belong to somebody. Most answers put it on the shelf.

Where a returned copy goes

The last arrow goes back to the question, not to the shelf. The next in the queue gets a turn.

Words

Five nouns that people mix up

WordIt isIdentityChanges?How many for two Draculas
TitleThe description: name, authorISBNHardly ever1
CopyThe thing with dust on itBarcodeStatus changes daily2
LoanOne copy with one member for a timeThe copy, while it runsDue date, when renewed0, 1 or 2
Hold requestA wish for any copy of a titleMember and titleMoves upAs many as wish
Kept copyA copy that waits on the hold shelfThe copyLapses after 3 days0, 1 or 2
An edition has its own ISBN, so the paperback and the hardback are two titles. Grouping editions as one work is a step further, and out of scope until asked.

Questions

Six questions, and what each answer changes

AskIf yesIf no
More than one copy of a title?Title and Copy are two classesOne class would do. Nobody says no
Different rules for different members?A Plan with numbers and a fine policyConstants
Can people wait for a title?A queue, a third state, an expiryA returned copy goes to the shelf
Must we know who had it last year?Loans are closed and keptThey may be removed. Ask about privacy
Several counters at once?One lock, or a databaseStill say what would break
E-books?Copies become licences: a count, not barcodesLeave it out

Design, first try

The design most people draw first

It follows the nouns of the prompt: a book, a member, a library. It works for one copy of each title, one kind of member and one counter. The trouble begins with the second copy.

The design to avoid: one class that does it all, and a book that is two things

LibrarySystem- instance: LibrarySystem- books: List<Book>- members: List<Member>+ getInstance()+ addBook(), search()+ borrow(), returnBook()+ fine(), sendEmail()

1/5One class for everything

Catalog, lending, fines and e-mail in one place. Four reasons to change, and no way to test fines without a library.

usesowns (dies together)extends (is a)

Python
book = library.find("111")             # Dracula: but which of the two?member.books.append(book)book.borrowed_by = member               # the same fact, a second timebook.due_date = today + timedelta(days=14)# the second copy of Dracula goes out:book.borrowed_by = other_member         # and the first loan is forgotten
Nothing is wrong with the code as such. The model has no place for the second loan.

Design, better

The design to reach

The design to reach: title and copy apart, the loan as an object

Library- members: Map<id, Member>- loans: Map<barcode, Loan>- lock: Lock+ checkout(member, barcode): Loan+ giveBack(barcode): fine+ hold(member, isbn): place+ renew(barcode): due+ lapse(): int

1/6One door

Library is what a counter, a kiosk or a web page talks to. Five verbs, one lock, no printing and no e-mail.

owns (dies together)usesimplements

A copy that is kept says for whom and until when. There is no reservation object for it, because nothing else would live in it.
Python
loan = library.checkout("sam", "D1")    # a Loan, or Refused with a reasonplace = library.hold("noor", "111")     # the place in the queue for a titlefine = library.give_back("D1")          # cents, and the copy is passed on
Lending speaks in barcodes, waiting speaks in ISBNs. If a signature mixes them up, the model is mixed up.

A return that somebody waits for

The message is the last step and outside the lock. A slow mail server must not stop the counter.

Roles

What each class owns

ClassKnowsDoesDoes not
LibraryMembers, running loans, the lockChecks rules, opens and closes loans, passes copies onSend mail, print, take cards
CatalogTitles, copies, the word indexFindsDecide who may borrow
WaitingListWho waits for which titleJoins, leaves, takes the firstKnow about copies
CopyIts status, and for whom it is keptNothing. It is a recordKnow the borrower
LoanCopy, member, plan, due dayNothing. It is a recordCalculate its fine
PlanLimit, days, renewalsNothingKnow its members
FinePolicyRate, grace, capDays to centsKnow dates

The life of a copy

There is no arrow from the shelf to Kept by a hold: if a copy is on the shelf, take it. A library with a web page adds that arrow.

The life of a membership

Our code needs one bit of it: may they borrow or not. Owing too much is not a state here, because paying must lift it at once: it is calculated.

The hard part

Three facts that must agree

The status of the copy, the set in the member and the table of loans tell one story in three places. We keep all three because each answers a question in O(1): is it here, may they take more, who has it. That is allowed under two conditions: one method writes all three, under one lock, and a test compares them.

Rule that is always trueBroken by
A copy is ON_LOAN exactly if there is a loan for its barcodeClosing a loan without passing the copy on
member.loans is the set of barcodes of their loansA list in the member that another class changes
A copy has kept_for exactly if it is KEPTClearing the status and not the name
If anyone waits for a title, none of its copies is on the shelfPutting a returned or new copy on the shelf without asking
Nobody waits for a title they hold or have keptLetting a borrower join the queue
The fourth is the heart of holds. It also explains why add_copy asks the waiting list: a new copy is a return that nobody made.

Where do you write down who has a copy?

BreaksIn the book
How
book.borrowed_by = member.
Limit
One loan for each title, and no history. member.books repeats it.
Choose when
A shelf at home.
WorksIn the copy
How
copy.borrowed_by and copy.due.
Limit
Correct while it runs. Renewals, plan and history have no place, and the copy knows people.
Choose when
If nobody asks about history.
StrongIn a loan
How
One record: copy, member, plan, due, renewals. Found by barcode.
Limit
One more class.
Choose when
Here. A relation with its own data is a class.

Money

Fines: days to cents

The fine is the part people expect to be a Strategy, and it is. Look at what varies. Standard and student differ by a number. A grace of three days is another shape, though one formula still covers both. No fine at all is a third.

Days lateRegular, 50 a dayStudent, 25, cap 1000Premium, 50, 3 days graceStaff
00000
31507500
4200100500
52501251000
502500100023500
602500 (cap)1000 (cap)2500 (cap)0
Whole cents. 5 days at 50 cents are 250 cents, which is 2.50. The cap of the regular plan, 2500, is reached on day 50.

Holds up

  • Cents as integers
  • Calendar days from date, not hours from datetime
  • The plan is stored in the loan when it starts
  • The policy gets a number of days and knows nothing else

Breaks

  • double for money
  • now - due in seconds, divided by 86,400
  • Reading the plan of today for a loan of last month
  • A setStrategy on one shared calculator: two counters, one strategy

Is it a number or a behaviour?

Limit, days and renewals stop at the first question. Fines reach the last one. Subclasses of Member are nowhere in the picture.

Two counters

The same copy, the same moment

Asha and Lee want one copy. At a desk this is impossible: the book is in one hand. Online it is normal, because both see *available* on a screen. So the check and the change must be one step. For one process a lock does it: the numbers are in the FAANG interview pages of the Solution.

Why the limit needs the lock too

Two different books, so a lock for each book does not help. The limit belongs to the member, and the lock must cover the member.

Summary

The whole topic in one minute.

A title is a description and a copy is a thing. Members borrow copies and wait for titles. The loan is an object that knows the copy, the member, the plan and the due day. Kinds of members are plans with numbers; only the fine is a strategy.

A copy that becomes free goes to the first who waits, under the same lock that closed the loan, and only then to the shelf. A kept copy lapses to the next person. Messages are written with the change and sent after it.

  • A title is a description, a copy is a thing. Lend copies, wait for titles.
  • The loan is an object: copy, member, plan, due day.
  • Kinds of member are a plan with numbers. Only the fine is behaviour.
  • A copy that comes back goes to the first who waits, and only then to the shelf.
  • Kept is a state with a name and a last day. It lapses to the next, not to the shelf.
  • One lock covers copy, member and queue. Messages go out after it.
  • If three places say the same thing, one method writes them and a test compares them.

Sources