Meet the Library API: Plan It, Build It
The fourth pass starts with a community library's checkout service, planned as a class diagram and built as version 1 in five languages, and then asked the question every pass starts with: what's likely to change? The answer shows why a class that builds its own storage and reads the real clock will hurt.
Journeyman · OOP · Software Development · Updated
After this lesson you can
- Plan a web API's first version as a class diagram, including what each class builds or reads for itself
- Spot what a class builds or reaches for inside itself, and say why that makes it hard to test and change
Key takeaways
- A class diagram can show what a class builds or reaches for inside itself, not only what it holds.
- Version 1 of the checkout service works: it lends a book for 14 days and charges $0.25 a day late, at most $5.
- It builds its own database connection and reads the computer's clock, so nothing outside it can change either one.
- That makes the late-fee rules impossible to test without waiting, and the storage impossible to swap: the problems this pass solves.
Before this: Meet the Bakery App (planning with a class diagram) and Why Singleton Is Usually a Trap (a hidden dependency).
The first three passes built apps that ran on their own. Most apps at work run on a framework: ASP.NET Core, Spring Boot, FastAPI, Express, Angular. A framework is a big set of ready-made code that runs your app and calls the parts you write. It can feel like magic the first week. It isn't: frameworks are built from the same patterns this course teaches, and this pass finds them. It starts the way every pass does, with a small app that works.
What the app does
Riverside Community Library lends books. A member (Maya, Sam or Priya) borrows a book, such as The Lighthouse Keeper, for 14 days. A book returned late costs $0.25 for each day past its due date, and never more than $5 a book. A member can have up to 5 books out at once.
The library wants this as a web API: other programs (the library's website, a phone app, the self-checkout kiosk) send it requests over the internet, and it answers with data. Version 1 starts with the part that does the real work, the checkout service. The web part comes in the next chapter.
Plan it: a class diagram first
The nouns in the story are a loan (who borrowed which title, and when it's due) and the checkout service that lends and takes back books. The loans have to be kept somewhere that survives a restart, so there's a database too.

This diagram shows something the bakery's didn't: arrows for what a class builds or reaches for inside itself. The checkout service builds its own database connection, and it reads the computer's clock to find out what day it is. Mark those arrows when you plan. They're the ones that decide how easy a class is to test.
Build version 1
LibraryDatabase here stands in for a real database connection: it prints that it's connecting, and keeps rows (a row is one record: a member, a title and a due date) in memory, so the program runs anywhere. The fee is worked out in cents, so $1.50 is 150, and printed as dollars at the end:
CheckoutService service = new CheckoutService();
Loan loan = service.Borrow("Maya", "The Lighthouse Keeper");
Console.WriteLine( quot;Loan {loan.Id}: {loan.Member} borrowed {loan.Title}, due in 14 days");
int fee = service.ReturnBook(loan.Id);
Console.WriteLine( quot;Loan {loan.Id} returned today: late fee ${fee / 100}.{fee % 100:00}");
record Loan(int Id, string Member, string Title, DateOnly Due);
// Stands in for a real database connection: it keeps rows in tables, by id.
class LibraryDatabase
{
private readonly Dictionary<string, List<Dictionary<string, string>>> tables = new();
public LibraryDatabase(string address) => Console.WriteLine( quot;Connecting to {address}...");
public int Insert(string table, Dictionary<string, string> row)
{
if (!tables.ContainsKey(table)) { tables[table] = new(); }
tables[table].Add(row);
return tables[table].Count;
}
public Dictionary<string, string> Select(string table, int id) => tables[table][id - 1];
}
class CheckoutService
{
// It builds its own database connection...
private readonly LibraryDatabase database = new LibraryDatabase("riverside-db");
public Loan Borrow(string member, string title)
{
// ...and reads the computer's clock.
DateOnly due = DateOnly.FromDateTime(DateTime.Today).AddDays(14);
int id = database.Insert("loans", new() { ["member"] = member, ["title"] = title, ["due"] = due.ToString("yyyy-MM-dd") });
return new Loan(id, member, title, due);
}
public int ReturnBook(int id)
{
DateOnly due = DateOnly.ParseExact(database.Select("loans", id)["due"], "yyyy-MM-dd");
int daysLate = Math.Max(0, DateOnly.FromDateTime(DateTime.Today).DayNumber - due.DayNumber);
return Math.Min(daysLate * 25, 500);
}
}
Connecting to riverside-db...
Loan 1: Maya borrowed The Lighthouse Keeper, due in 14 days
Loan 1 returned today: late fee $0.00
record Loan(int id, String member, String title, LocalDate due) { }
// Stands in for a real database connection: it keeps rows in tables, by id.
class LibraryDatabase {
private final Map<String, List<Map<String, String>>> tables = new HashMap<>();
LibraryDatabase(String address) { IO.println("Connecting to " + address + "..."); }
int insert(String table, Map<String, String> row) {
tables.computeIfAbsent(table, name -> new ArrayList<>()).add(row);
return tables.get(table).size();
}
Map<String, String> select(String table, int id) { return tables.get(table).get(id - 1); }
}
class CheckoutService {
// It builds its own database connection...
private final LibraryDatabase database = new LibraryDatabase("riverside-db");
Loan borrow(String member, String title) {
// ...and reads the computer's clock.
LocalDate due = LocalDate.now().plusDays(14);
int id = database.insert("loans", Map.of("member", member, "title", title, "due", due.toString()));
return new Loan(id, member, title, due);
}
int returnBook(int id) {
LocalDate due = LocalDate.parse(database.select("loans", id).get("due"));
long daysLate = Math.max(0, ChronoUnit.DAYS.between(due, LocalDate.now()));
return (int) Math.min(daysLate * 25, 500);
}
}
void main() {
CheckoutService service = new CheckoutService();
Loan loan = service.borrow("Maya", "The Lighthouse Keeper");
IO.println("Loan " + loan.id() + ": " + loan.member() + " borrowed " + loan.title() + ", due in 14 days");
int fee = service.returnBook(loan.id());
IO.println("Loan " + loan.id() + " returned today: late fee " + String.format("$%d.%02d", fee / 100, fee % 100));
}
Connecting to riverside-db...
Loan 1: Maya borrowed The Lighthouse Keeper, due in 14 days
Loan 1 returned today: late fee $0.00
from dataclasses import dataclass
from datetime import date, timedelta
@dataclass
class Loan:
id: int
member: str
title: str
due: date
class LibraryDatabase:
"""Stands in for a real database connection: it keeps rows in tables, by id."""
def __init__(self, address):
print(f"Connecting to {address}...")
self.tables = {}
def insert(self, table, row):
rows = self.tables.setdefault(table, [])
rows.append(row)
return len(rows)
def select(self, table, id):
return self.tables[table][id - 1]
class CheckoutService:
def __init__(self):
# It builds its own database connection...
self.database = LibraryDatabase("riverside-db")
def borrow(self, member, title):
# ...and reads the computer's clock.
due = date.today() + timedelta(days=14)
id = self.database.insert("loans", {"member": member, "title": title, "due": due.isoformat()})
return Loan(id, member, title, due)
def return_book(self, id):
due = date.fromisoformat(self.database.select("loans", id)["due"])
days_late = max(0, (date.today() - due).days)
return min(days_late * 25, 500)
service = CheckoutService()
loan = service.borrow("Maya", "The Lighthouse Keeper")
print(f"Loan {loan.id}: {loan.member} borrowed {loan.title}, due in 14 days")
fee = service.return_book(loan.id)
print(f"Loan {loan.id} returned today: late fee ${fee // 100}.{fee % 100:02d}")
Connecting to riverside-db...
Loan 1: Maya borrowed The Lighthouse Keeper, due in 14 days
Loan 1 returned today: late fee $0.00
const DAY = 24 * 60 * 60 * 1000;
class Loan {
constructor(id, member, title, due) {
this.id = id;
this.member = member;
this.title = title;
this.due = due;
}
}
// Stands in for a real database connection: it keeps rows in tables, by id.
class LibraryDatabase {
#tables = new Map();
constructor(address) { console.log(`Connecting to ${address}...`); }
insert(table, row) {
if (!this.#tables.has(table)) { this.#tables.set(table, []); }
this.#tables.get(table).push(row);
return this.#tables.get(table).length;
}
select(table, id) { return this.#tables.get(table)[id - 1]; }
}
class CheckoutService {
// It builds its own database connection...
#database = new LibraryDatabase("riverside-db");
borrow(member, title) {
// ...and reads the computer's clock. Dates are "YYYY-MM-DD" text.
const today = new Date().toISOString().slice(0, 10);
const due = new Date(Date.parse(today) + 14 * DAY).toISOString().slice(0, 10);
const id = this.#database.insert("loans", { member, title, due });
return new Loan(id, member, title, due);
}
returnBook(id) {
const today = new Date().toISOString().slice(0, 10);
const due = this.#database.select("loans", id).due;
const daysLate = Math.max(0, Math.round((Date.parse(today) - Date.parse(due)) / DAY));
return Math.min(daysLate * 25, 500);
}
}
const service = new CheckoutService();
const loan = service.borrow("Maya", "The Lighthouse Keeper");
console.log(`Loan ${loan.id}: ${loan.member} borrowed ${loan.title}, due in 14 days`);
const fee = service.returnBook(loan.id);
console.log(`Loan ${loan.id} returned today: late fee ${(fee / 100).toFixed(2)}`);
Connecting to riverside-db...
Loan 1: Maya borrowed The Lighthouse Keeper, due in 14 days
Loan 1 returned today: late fee $0.00
const DAY = 24 * 60 * 60 * 1000;
class Loan {
id: number;
member: string;
title: string;
due: string;
constructor(id: number, member: string, title: string, due: string) {
this.id = id;
this.member = member;
this.title = title;
this.due = due;
}
}
type Row = Record<string, string>;
// Stands in for a real database connection: it keeps rows in tables, by id.
class LibraryDatabase {
private tables = new Map<string, Row[]>();
constructor(address: string) { console.log(`Connecting to ${address}...`); }
insert(table: string, row: Row): number {
if (!this.tables.has(table)) { this.tables.set(table, []); }
this.tables.get(table)!.push(row);
return this.tables.get(table)!.length;
}
select(table: string, id: number): Row { return this.tables.get(table)![id - 1]; }
}
class CheckoutService {
// It builds its own database connection...
private database = new LibraryDatabase("riverside-db");
borrow(member: string, title: string): Loan {
// ...and reads the computer's clock. Dates are "YYYY-MM-DD" text.
const today = new Date().toISOString().slice(0, 10);
const due = new Date(Date.parse(today) + 14 * DAY).toISOString().slice(0, 10);
const id = this.database.insert("loans", { member, title, due });
return new Loan(id, member, title, due);
}
returnBook(id: number): number {
const today = new Date().toISOString().slice(0, 10);
const due = this.database.select("loans", id).due;
const daysLate = Math.max(0, Math.round((Date.parse(today) - Date.parse(due)) / DAY));
return Math.min(daysLate * 25, 500);
}
}
const service = new CheckoutService();
const loan = service.borrow("Maya", "The Lighthouse Keeper");
console.log(`Loan ${loan.id}: ${loan.member} borrowed ${loan.title}, due in 14 days`);
const fee = service.returnBook(loan.id);
console.log(`Loan ${loan.id} returned today: late fee ${(fee / 100).toFixed(2)}`);
Connecting to riverside-db...
Loan 1: Maya borrowed The Lighthouse Keeper, due in 14 days
Loan 1 returned today: late fee $0.00
Where the languages differ. Each language has its own date type: DateOnly in C#, LocalDate in Java and date in Python. JavaScript's Date always carries a time of day too, so the JavaScript and TypeScript tabs keep dates as "2026-03-16" text and work out the days between two of them.
It works. A loan goes into the database, and a book brought back the same day costs nothing. Like the bakery's version 1, it has no design pattern in it, and it doesn't need one to work.
Try it. Borrow a second book for Sam, Rivers of Glass, and print its loan. It should be loan 2.
What's likely to change?
The question every pass starts with: which parts of this app will change, and which won't? The library's staff already have answers.
| Likely to change | Why | Where it lives in version 1 |
|---|---|---|
| Where loans are kept | The library is moving to a new database server next year, and tests shouldn't need a database at all | new LibraryDatabase("riverside-db"), inside the service |
| What day it is | A test of a late fee needs "20 days after the book was borrowed", not today | the computer's clock, read inside the service |
| How requests arrive | The website, the phone app and the kiosk all send web requests, each needing a sign-in check and a log | nowhere yet |
| What each screen shows | The website shows a page of books; the phone app wants the same list as plain data | nowhere yet |
And some things almost never change: a loan has a member, a title and a due date, and the rules are 14 days, $0.25 a day, at most $5.
Why version 1 will hurt
The library's board asks a fair question: "Is a book returned 20 days after it was borrowed really charged $1.50?" (It's due on day 14, so it's 6 days late: 6 × $0.25.) To check, you'd have to borrow a book and wait 20 days. The service reads the real clock, and nothing outside it can tell it what day it is.
Read it as a doctor would:
- The symptom: a rule you can't test without waiting, and storage you can't swap without editing the service.
- The cause: the service builds its database and reaches for the clock inside itself. Look at
new CheckoutService(): nothing there says it needs a database or a clock. Both are hidden dependencies, the same trouble the bakery's Singleton caused in Pass 1, now twice over.
A dependency is anything a class needs in order to do its job. Needing things is fine. The trouble is a class that decides for itself which database and which clock, so nobody else can.
Where the patterns come from
Every row of the "likely to change" table turns into a problem in this pass, and each problem into a fix that frameworks are built on. This chapter hands the service what it needs instead of letting it build it (dependency injection), meets the part of a framework that does the handing out (a container), puts the loans behind one simple promise (a repository), and then shows the payoff: late-fee tests that run in milliseconds. The next chapter puts the API on the web.
Check yourself
2 questions to try on the lesson page.
So what
When you plan a class, draw what it builds and what it reaches for, not only what it holds. Those arrows tell you, before you write a test, which parts nobody else will be able to change. Version 1's two such arrows are what the rest of this chapter fixes.