# Repository: Ask for the Book, Not the Shelf

When the checkout service talks to the database in the database's own words (tables, rows, columns, dates stored as text), every class that needs loans copies that code, tests need a database, and a new database means editing them all; a repository puts loans behind one interface in the app's own words, so a class asks for a loan and never learns where it's kept.

Journeyman · OOP · Software Development · Updated November 17, 2026

By Gregor Dzierzon

## After this lesson you can

- Put storage behind a repository: one interface, in the app's own words, that saves and finds things whatever stores them
- Spot the smells that point to a repository: tables, rows and storage commands inside business code, copied into every class that needs the data

## Key takeaways

- The smell: tables, rows and storage commands inside business code, copied into every class that needs the data.
- The cause: the service depends on how loans are stored, not on what it needs from them.
- The fix: one interface in the app's words (add a loan, find loan 1), kept by a class for each place loans can live: the library database, or memory for tests.
- A repository hides where things are kept. The rules about them, such as late fees, stay in the service.

**Before this:** *Dependency Injection: Hand Me What I Need*, and interfaces.

The checkout service is handed its database and its clock now, and the late-fee test passes. Two things still bother the team. The test connects to a database to run, and the library's IT staff have news: next year the loans move to a new database, CloudShelf, which doesn't store rows at all. Look at how much of the service would have to change. By the end of this lesson, none of it will, and the fix has a plain name: a *repository*.

## The symptom: the service speaks the database's language

Here is the service as the last lesson left it, and a second class that needs loans, the overdue notice. Watch for the words that are about *storing* loans rather than lending books: `"loans"` (a table's name), rows, columns, and dates turned into text and back:

```csharp
// The test: a fixed clock, and still a database.
FixedClock clock = new FixedClock(new DateOnly(2026, 3, 2));
LibraryDatabase database = new LibraryDatabase("test-db");
CheckoutService service = new CheckoutService(database, clock);
Loan loan = service.Borrow("Maya", "The Lighthouse Keeper");
clock.Today = clock.Today.AddDays(20);
int fee = service.ReturnBook(loan.Id);
Console.WriteLine($"Returned 20 days later: late fee ${fee / 100}.{fee % 100:00}, " + (fee == 150 ? "passed" : "failed"));
Console.WriteLine("Notice: " + new OverdueNotice(database).For(loan.Id));

record Loan(int Id, string Member, string Title, DateOnly Due);
interface IClock { DateOnly Today { get; } }
class FixedClock : IClock { public FixedClock(DateOnly today) => Today = today; public DateOnly Today { get; set; } }

class LibraryDatabase
{
    private readonly Dictionary<string, List<Dictionary<string, string>>> tables = new();
    public LibraryDatabase(string address) => Console.WriteLine($"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
{
    private readonly LibraryDatabase database;
    private readonly IClock clock;
    public CheckoutService(LibraryDatabase database, IClock clock) { this.database = database; this.clock = clock; }

    public Loan Borrow(string member, string title)
    {
        DateOnly due = clock.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");
        return Math.Min(Math.Max(0, clock.Today.DayNumber - due.DayNumber) * 25, 500);
    }
}

// A second class that needs loans, and reads the same table and columns itself.
class OverdueNotice
{
    private readonly LibraryDatabase database;
    public OverdueNotice(LibraryDatabase database) => this.database = database;

    public string For(int id)
    {
        Dictionary<string, string> row = database.Select("loans", id);
        return $"{row["member"]}, {row["title"]}, was due {row["due"]}";
    }
}
```

```text
Connecting to test-db...
Returned 20 days later: late fee $1.50, passed
Notice: Maya, The Lighthouse Keeper, was due 2026-03-16
```

```java
record Loan(int id, String member, String title, LocalDate due) { }
interface Clock { LocalDate today(); }
class FixedClock implements Clock { LocalDate day; FixedClock(LocalDate day) { this.day = day; } public LocalDate today() { return day; } }

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 {
    private final LibraryDatabase database;
    private final Clock clock;
    CheckoutService(LibraryDatabase database, Clock clock) { this.database = database; this.clock = clock; }

    Loan borrow(String member, String title) {
        LocalDate due = clock.today().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"));
        return (int) Math.min(Math.max(0, ChronoUnit.DAYS.between(due, clock.today())) * 25, 500);
    }
}

// A second class that needs loans, and reads the same table and columns itself.
class OverdueNotice {
    private final LibraryDatabase database;
    OverdueNotice(LibraryDatabase database) { this.database = database; }

    String forLoan(int id) {
        Map<String, String> row = database.select("loans", id);
        return row.get("member") + ", " + row.get("title") + ", was due " + row.get("due");
    }
}

void main() {
    // The test: a fixed clock, and still a database.
    FixedClock clock = new FixedClock(LocalDate.of(2026, 3, 2));
    LibraryDatabase database = new LibraryDatabase("test-db");
    CheckoutService service = new CheckoutService(database, clock);
    Loan loan = service.borrow("Maya", "The Lighthouse Keeper");
    clock.day = clock.day.plusDays(20);
    int fee = service.returnBook(loan.id());
    IO.println(String.format("Returned 20 days later: late fee $%d.%02d, ", fee / 100, fee % 100) + (fee == 150 ? "passed" : "failed"));
    IO.println("Notice: " + new OverdueNotice(database).forLoan(loan.id()));
}
```

```text
Connecting to test-db...
Returned 20 days later: late fee $1.50, passed
Notice: Maya, The Lighthouse Keeper, was due 2026-03-16
```

```python
from dataclasses import dataclass
from datetime import date, timedelta


@dataclass
class Loan:
    id: int
    member: str
    title: str
    due: date


class FixedClock:
    def __init__(self, day):
        self.day = day

    def today(self):
        return self.day


class LibraryDatabase:
    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, database, clock):
        self.database = database
        self.clock = clock

    def borrow(self, member, title):
        due = self.clock.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"])
        return min(max(0, (self.clock.today() - due).days) * 25, 500)


class OverdueNotice:
    """A second class that needs loans, and reads the same table and columns itself."""

    def __init__(self, database):
        self.database = database

    def for_loan(self, id):
        row = self.database.select("loans", id)
        return f"{row['member']}, {row['title']}, was due {row['due']}"


# The test: a fixed clock, and still a database.
clock = FixedClock(date(2026, 3, 2))
database = LibraryDatabase("test-db")
service = CheckoutService(database, clock)
loan = service.borrow("Maya", "The Lighthouse Keeper")
clock.day += timedelta(days=20)
fee = service.return_book(loan.id)
print(f"Returned 20 days later: late fee ${fee // 100}.{fee % 100:02d}, " + ("passed" if fee == 150 else "failed"))
print("Notice: " + OverdueNotice(database).for_loan(loan.id))
```

```text
Connecting to test-db...
Returned 20 days later: late fee $1.50, passed
Notice: Maya, The Lighthouse Keeper, was due 2026-03-16
```

```javascript
const DAY = 24 * 60 * 60 * 1000;
const addDays = (day, days) => new Date(Date.parse(day) + days * DAY).toISOString().slice(0, 10);
const daysBetween = (from, to) => Math.round((Date.parse(to) - Date.parse(from)) / DAY);

class FixedClock { constructor(day) { this.day = day; } today() { return this.day; } }

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 {
  #database;
  #clock;
  constructor(database, clock) { this.#database = database; this.#clock = clock; }

  borrow(member, title) {
    const due = addDays(this.#clock.today(), 14);
    const id = this.#database.insert("loans", { member, title, due });
    return { id, member, title, due };
  }

  returnBook(id) {
    const due = this.#database.select("loans", id).due;
    return Math.min(Math.max(0, daysBetween(due, this.#clock.today())) * 25, 500);
  }
}

// A second class that needs loans, and reads the same table and columns itself.
class OverdueNotice {
  #database;
  constructor(database) { this.#database = database; }
  for(id) {
    const row = this.#database.select("loans", id);
    return `${row.member}, ${row.title}, was due ${row.due}`;
  }
}

// The test: a fixed clock, and still a database.
const clock = new FixedClock("2026-03-02");
const database = new LibraryDatabase("test-db");
const service = new CheckoutService(database, clock);
const loan = service.borrow("Maya", "The Lighthouse Keeper");
clock.day = addDays(clock.day, 20);
const fee = service.returnBook(loan.id);
console.log(`Returned 20 days later: late fee $${(fee / 100).toFixed(2)}, ` + (fee === 150 ? "passed" : "failed"));
console.log("Notice: " + new OverdueNotice(database).for(loan.id));
```

```text
Connecting to test-db...
Returned 20 days later: late fee $1.50, passed
Notice: Maya, The Lighthouse Keeper, was due 2026-03-16
```

```typescript
const DAY = 24 * 60 * 60 * 1000;
const addDays = (day: string, days: number): string => new Date(Date.parse(day) + days * DAY).toISOString().slice(0, 10);
const daysBetween = (from: string, to: string): number => Math.round((Date.parse(to) - Date.parse(from)) / DAY);

interface Loan { id: number; member: string; title: string; due: string; }
type Row = Record<string, string>;
interface Clock { today(): string; }
class FixedClock implements Clock { day: string; constructor(day: string) { this.day = day; } today(): string { return this.day; } }

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 {
  private readonly database: LibraryDatabase;
  private readonly clock: Clock;
  constructor(database: LibraryDatabase, clock: Clock) { this.database = database; this.clock = clock; }

  borrow(member: string, title: string): Loan {
    const due = addDays(this.clock.today(), 14);
    const id = this.database.insert("loans", { member, title, due });
    return { id, member, title, due };
  }

  returnBook(id: number): number {
    const due = this.database.select("loans", id).due;
    return Math.min(Math.max(0, daysBetween(due, this.clock.today())) * 25, 500);
  }
}

// A second class that needs loans, and reads the same table and columns itself.
class OverdueNotice {
  private readonly database: LibraryDatabase;
  constructor(database: LibraryDatabase) { this.database = database; }
  for(id: number): string {
    const row = this.database.select("loans", id);
    return `${row.member}, ${row.title}, was due ${row.due}`;
  }
}

// The test: a fixed clock, and still a database.
const clock = new FixedClock("2026-03-02");
const database = new LibraryDatabase("test-db");
const service = new CheckoutService(database, clock);
const loan = service.borrow("Maya", "The Lighthouse Keeper");
clock.day = addDays(clock.day, 20);
const fee = service.returnBook(loan.id);
console.log(`Returned 20 days later: late fee $${(fee / 100).toFixed(2)}, ` + (fee === 150 ? "passed" : "failed"));
console.log("Notice: " + new OverdueNotice(database).for(loan.id));
```

```text
Connecting to test-db...
Returned 20 days later: late fee $1.50, passed
Notice: Maya, The Lighthouse Keeper, was due 2026-03-16
```

It works, and the test passes. But count the lines that are about lending books, and the ones about storing them. The table's name, the column names and the date-as-text are in both classes. When CloudShelf arrives, every one of those lines changes, in every class that needs a loan. And the test still opens a database connection, because the service asks for the one class `LibraryDatabase`.

- **The symptom:** tables, rows and storage commands inside business code (the code that holds the library's rules), copied into every class that needs the data.
- **The cause:** the service depends on *how* loans are stored, when all it needs is to save a loan and find one again.

## What would you try?

**Give the tests a database of their own.** It works, slowly. Every test run needs a database server set up, and tests that share one can change each other's results, the Singleton trouble from Pass 1 in a new place.

**A fake `LibraryDatabase` for tests that pretends to be one.** Now the fake has to speak the database's language too: tables, rows, dates as text. Rename a column and the fakes break, though no rule changed.

**Private helper methods inside the service for the row code.** Tidier, but the service still depends on `LibraryDatabase`, and the overdue notice still has its own copy.

What a good fix needs: the service should ask for loans in its own words, "add this loan", "find loan 1", and something else should know where they're kept.

## The fix: ask for the book, not the shelf

At the library's front desk you ask for *The Lighthouse Keeper*, and the librarian comes back with it. You don't need to know it's on shelf 3B in the basement, or that last month it was in the annex. If the library moves its shelves, you still ask the same way.

![A library's front desk: a member asks the librarian "The Lighthouse Keeper, please", and behind the librarian a doorway leads to rows of tall shelves, one of them labeled "3B", where the librarian is fetching the book](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/c90b710bb72747c499e9f67fc8ce7916.webp)

In code, the desk is one interface, a **loan repository**, in the service's own words: **add a loan** and **find a loan**. One class keeps that promise with the library database, and it's the only class that knows tables, rows and columns. Another keeps it in memory, for tests. The service asks for "a loan repository" and never learns which one it got:

![Repository's roles: the checkout service and the overdue notice ask the loan repository to add a loan and find loan 1, one promise in the app's own words. In a fence labeled "what changes: where loans are kept", DatabaseLoans and InMemoryLoans (for tests) each keep the promise](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/b43855f161b3407e8bf5b11a2852b210.webp)

## How it got its name

A **repository** is a store where things are kept and found again, and the **Repository pattern** puts a collection of things (loans, books, members) behind one interface that looks like a simple list: add one, find one, find all of Maya's. Teams building business apps kept landing on it, and it was written up in the early 2000s, in books about building business software. It's not in the 1994 book, but nearly every framework that talks to a database has it built in.

## The classic version: an interface and two keepers

```csharp
// The test: a fixed clock and loans kept in memory. No database.
FixedClock clock = new FixedClock(new DateOnly(2026, 3, 2));
ILoanRepository loans = new InMemoryLoans();
CheckoutService service = new CheckoutService(loans, clock);
Loan loan = service.Borrow("Maya", "The Lighthouse Keeper");
clock.Today = clock.Today.AddDays(20);
int fee = service.ReturnBook(loan.Id);
Console.WriteLine($"Returned 20 days later: late fee ${fee / 100}.{fee % 100:00}, " + (fee == 150 ? "passed" : "failed"));
Console.WriteLine("Notice: " + new OverdueNotice(loans).For(loan.Id));

// The app: loans kept in the library's database.
CheckoutService app = new CheckoutService(new DatabaseLoans(new LibraryDatabase("riverside-db")), clock);
Console.WriteLine($"App: loan {app.Borrow("Sam", "Rivers of Glass").Id} is in the library database");

record Loan(int Id, string Member, string Title, DateOnly Due);
interface IClock { DateOnly Today { get; } }
class FixedClock : IClock { public FixedClock(DateOnly today) => Today = today; public DateOnly Today { get; set; } }

// The promise, in the app's own words.
interface ILoanRepository
{
    Loan Add(string member, string title, DateOnly due);
    Loan Find(int id);
}

// Keeps loans in the library's database: the only class that knows tables, rows and columns.
class DatabaseLoans : ILoanRepository
{
    private readonly LibraryDatabase database;
    public DatabaseLoans(LibraryDatabase database) => this.database = database;

    public Loan Add(string member, string title, DateOnly due)
    {
        int id = database.Insert("loans", new() { ["member"] = member, ["title"] = title, ["due"] = due.ToString("yyyy-MM-dd") });
        return new Loan(id, member, title, due);
    }

    public Loan Find(int id)
    {
        Dictionary<string, string> row = database.Select("loans", id);
        return new Loan(id, row["member"], row["title"], DateOnly.ParseExact(row["due"], "yyyy-MM-dd"));
    }
}

// Keeps loans in memory: for tests, and for trying the app out.
class InMemoryLoans : ILoanRepository
{
    private readonly List<Loan> loans = new();

    public Loan Add(string member, string title, DateOnly due)
    {
        Loan loan = new Loan(loans.Count + 1, member, title, due);
        loans.Add(loan);
        return loan;
    }

    public Loan Find(int id) => loans[id - 1];
}

class LibraryDatabase
{
    private readonly Dictionary<string, List<Dictionary<string, string>>> tables = new();
    public LibraryDatabase(string address) => Console.WriteLine($"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];
}

// The service speaks only about loans now.
class CheckoutService
{
    private readonly ILoanRepository loans;
    private readonly IClock clock;
    public CheckoutService(ILoanRepository loans, IClock clock) { this.loans = loans; this.clock = clock; }

    public Loan Borrow(string member, string title) => loans.Add(member, title, clock.Today.AddDays(14));

    public int ReturnBook(int id)
    {
        Loan loan = loans.Find(id);
        return Math.Min(Math.Max(0, clock.Today.DayNumber - loan.Due.DayNumber) * 25, 500);
    }
}

class OverdueNotice
{
    private readonly ILoanRepository loans;
    public OverdueNotice(ILoanRepository loans) => this.loans = loans;

    public string For(int id)
    {
        Loan loan = loans.Find(id);
        return $"{loan.Member}, {loan.Title}, was due {loan.Due:yyyy-MM-dd}";
    }
}
```

```text
Returned 20 days later: late fee $1.50, passed
Notice: Maya, The Lighthouse Keeper, was due 2026-03-16
Connecting to riverside-db...
App: loan 1 is in the library database
```

```java
record Loan(int id, String member, String title, LocalDate due) { }
interface Clock { LocalDate today(); }
class FixedClock implements Clock { LocalDate day; FixedClock(LocalDate day) { this.day = day; } public LocalDate today() { return day; } }

// The promise, in the app's own words.
interface LoanRepository {
    Loan add(String member, String title, LocalDate due);
    Loan find(int id);
}

// Keeps loans in the library's database: the only class that knows tables, rows and columns.
class DatabaseLoans implements LoanRepository {
    private final LibraryDatabase database;
    DatabaseLoans(LibraryDatabase database) { this.database = database; }

    public Loan add(String member, String title, LocalDate due) {
        int id = database.insert("loans", Map.of("member", member, "title", title, "due", due.toString()));
        return new Loan(id, member, title, due);
    }

    public Loan find(int id) {
        Map<String, String> row = database.select("loans", id);
        return new Loan(id, row.get("member"), row.get("title"), LocalDate.parse(row.get("due")));
    }
}

// Keeps loans in memory: for tests, and for trying the app out.
class InMemoryLoans implements LoanRepository {
    private final List<Loan> loans = new ArrayList<>();

    public Loan add(String member, String title, LocalDate due) {
        Loan loan = new Loan(loans.size() + 1, member, title, due);
        loans.add(loan);
        return loan;
    }

    public Loan find(int id) { return loans.get(id - 1); }
}

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); }
}

// The service speaks only about loans now.
class CheckoutService {
    private final LoanRepository loans;
    private final Clock clock;
    CheckoutService(LoanRepository loans, Clock clock) { this.loans = loans; this.clock = clock; }

    Loan borrow(String member, String title) { return loans.add(member, title, clock.today().plusDays(14)); }

    int returnBook(int id) {
        Loan loan = loans.find(id);
        return (int) Math.min(Math.max(0, ChronoUnit.DAYS.between(loan.due(), clock.today())) * 25, 500);
    }
}

class OverdueNotice {
    private final LoanRepository loans;
    OverdueNotice(LoanRepository loans) { this.loans = loans; }

    String forLoan(int id) {
        Loan loan = loans.find(id);
        return loan.member() + ", " + loan.title() + ", was due " + loan.due();
    }
}

void main() {
    // The test: a fixed clock and loans kept in memory. No database.
    FixedClock clock = new FixedClock(LocalDate.of(2026, 3, 2));
    LoanRepository loans = new InMemoryLoans();
    CheckoutService service = new CheckoutService(loans, clock);
    Loan loan = service.borrow("Maya", "The Lighthouse Keeper");
    clock.day = clock.day.plusDays(20);
    int fee = service.returnBook(loan.id());
    IO.println(String.format("Returned 20 days later: late fee $%d.%02d, ", fee / 100, fee % 100) + (fee == 150 ? "passed" : "failed"));
    IO.println("Notice: " + new OverdueNotice(loans).forLoan(loan.id()));

    // The app: loans kept in the library's database.
    CheckoutService app = new CheckoutService(new DatabaseLoans(new LibraryDatabase("riverside-db")), clock);
    IO.println("App: loan " + app.borrow("Sam", "Rivers of Glass").id() + " is in the library database");
}
```

```text
Returned 20 days later: late fee $1.50, passed
Notice: Maya, The Lighthouse Keeper, was due 2026-03-16
Connecting to riverside-db...
App: loan 1 is in the library database
```

```python
from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import date, timedelta


@dataclass
class Loan:
    id: int
    member: str
    title: str
    due: date


class FixedClock:
    def __init__(self, day):
        self.day = day

    def today(self):
        return self.day


class LoanRepository(ABC):
    """The promise, in the app's own words."""

    @abstractmethod
    def add(self, member, title, due): ...

    @abstractmethod
    def find(self, id): ...


class DatabaseLoans(LoanRepository):
    """Keeps loans in the library's database: the only class that knows tables, rows and columns."""

    def __init__(self, database):
        self.database = database

    def add(self, member, title, due):
        id = self.database.insert("loans", {"member": member, "title": title, "due": due.isoformat()})
        return Loan(id, member, title, due)

    def find(self, id):
        row = self.database.select("loans", id)
        return Loan(id, row["member"], row["title"], date.fromisoformat(row["due"]))


class InMemoryLoans(LoanRepository):
    """Keeps loans in memory: for tests, and for trying the app out."""

    def __init__(self):
        self.loans = []

    def add(self, member, title, due):
        loan = Loan(len(self.loans) + 1, member, title, due)
        self.loans.append(loan)
        return loan

    def find(self, id):
        return self.loans[id - 1]


class LibraryDatabase:
    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:
    """The service speaks only about loans now."""

    def __init__(self, loans, clock):
        self.loans = loans
        self.clock = clock

    def borrow(self, member, title):
        return self.loans.add(member, title, self.clock.today() + timedelta(days=14))

    def return_book(self, id):
        loan = self.loans.find(id)
        return min(max(0, (self.clock.today() - loan.due).days) * 25, 500)


class OverdueNotice:
    def __init__(self, loans):
        self.loans = loans

    def for_loan(self, id):
        loan = self.loans.find(id)
        return f"{loan.member}, {loan.title}, was due {loan.due.isoformat()}"


# The test: a fixed clock and loans kept in memory. No database.
clock = FixedClock(date(2026, 3, 2))
loans = InMemoryLoans()
service = CheckoutService(loans, clock)
loan = service.borrow("Maya", "The Lighthouse Keeper")
clock.day += timedelta(days=20)
fee = service.return_book(loan.id)
print(f"Returned 20 days later: late fee ${fee // 100}.{fee % 100:02d}, " + ("passed" if fee == 150 else "failed"))
print("Notice: " + OverdueNotice(loans).for_loan(loan.id))

# The app: loans kept in the library's database.
app = CheckoutService(DatabaseLoans(LibraryDatabase("riverside-db")), clock)
print(f"App: loan {app.borrow('Sam', 'Rivers of Glass').id} is in the library database")
```

```text
Returned 20 days later: late fee $1.50, passed
Notice: Maya, The Lighthouse Keeper, was due 2026-03-16
Connecting to riverside-db...
App: loan 1 is in the library database
```

```javascript
const DAY = 24 * 60 * 60 * 1000;
const addDays = (day, days) => new Date(Date.parse(day) + days * DAY).toISOString().slice(0, 10);
const daysBetween = (from, to) => Math.round((Date.parse(to) - Date.parse(from)) / DAY);

class FixedClock { constructor(day) { this.day = day; } today() { return this.day; } }

// Two keepers of the same promise: add(member, title, due) and find(id).

// Keeps loans in the library's database: the only class that knows tables, rows and columns.
class DatabaseLoans {
  #database;
  constructor(database) { this.#database = database; }
  add(member, title, due) {
    const id = this.#database.insert("loans", { member, title, due });
    return { id, member, title, due };
  }
  find(id) {
    const row = this.#database.select("loans", id);
    return { id, member: row.member, title: row.title, due: row.due };
  }
}

// Keeps loans in memory: for tests, and for trying the app out.
class InMemoryLoans {
  #loans = [];
  add(member, title, due) {
    const loan = { id: this.#loans.length + 1, member, title, due };
    this.#loans.push(loan);
    return loan;
  }
  find(id) { return this.#loans[id - 1]; }
}

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]; }
}

// The service speaks only about loans now.
class CheckoutService {
  #loans;
  #clock;
  constructor(loans, clock) { this.#loans = loans; this.#clock = clock; }
  borrow(member, title) { return this.#loans.add(member, title, addDays(this.#clock.today(), 14)); }
  returnBook(id) {
    const loan = this.#loans.find(id);
    return Math.min(Math.max(0, daysBetween(loan.due, this.#clock.today())) * 25, 500);
  }
}

class OverdueNotice {
  #loans;
  constructor(loans) { this.#loans = loans; }
  for(id) {
    const loan = this.#loans.find(id);
    return `${loan.member}, ${loan.title}, was due ${loan.due}`;
  }
}

// The test: a fixed clock and loans kept in memory. No database.
const clock = new FixedClock("2026-03-02");
const loans = new InMemoryLoans();
const service = new CheckoutService(loans, clock);
const loan = service.borrow("Maya", "The Lighthouse Keeper");
clock.day = addDays(clock.day, 20);
const fee = service.returnBook(loan.id);
console.log(`Returned 20 days later: late fee $${(fee / 100).toFixed(2)}, ` + (fee === 150 ? "passed" : "failed"));
console.log("Notice: " + new OverdueNotice(loans).for(loan.id));

// The app: loans kept in the library's database.
const app = new CheckoutService(new DatabaseLoans(new LibraryDatabase("riverside-db")), clock);
console.log(`App: loan ${app.borrow("Sam", "Rivers of Glass").id} is in the library database`);
```

```text
Returned 20 days later: late fee $1.50, passed
Notice: Maya, The Lighthouse Keeper, was due 2026-03-16
Connecting to riverside-db...
App: loan 1 is in the library database
```

```typescript
const DAY = 24 * 60 * 60 * 1000;
const addDays = (day: string, days: number): string => new Date(Date.parse(day) + days * DAY).toISOString().slice(0, 10);
const daysBetween = (from: string, to: string): number => Math.round((Date.parse(to) - Date.parse(from)) / DAY);

interface Loan { id: number; member: string; title: string; due: string; }
type Row = Record<string, string>;
interface Clock { today(): string; }
class FixedClock implements Clock { day: string; constructor(day: string) { this.day = day; } today(): string { return this.day; } }

// The promise, in the app's own words.
interface LoanRepository {
  add(member: string, title: string, due: string): Loan;
  find(id: number): Loan;
}

// Keeps loans in the library's database: the only class that knows tables, rows and columns.
class DatabaseLoans implements LoanRepository {
  private readonly database: LibraryDatabase;
  constructor(database: LibraryDatabase) { this.database = database; }
  add(member: string, title: string, due: string): Loan {
    const id = this.database.insert("loans", { member, title, due });
    return { id, member, title, due };
  }
  find(id: number): Loan {
    const row = this.database.select("loans", id);
    return { id, member: row.member, title: row.title, due: row.due };
  }
}

// Keeps loans in memory: for tests, and for trying the app out.
class InMemoryLoans implements LoanRepository {
  private loans: Loan[] = [];
  add(member: string, title: string, due: string): Loan {
    const loan = { id: this.loans.length + 1, member, title, due };
    this.loans.push(loan);
    return loan;
  }
  find(id: number): Loan { return this.loans[id - 1]; }
}

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]; }
}

// The service speaks only about loans now.
class CheckoutService {
  private readonly loans: LoanRepository;
  private readonly clock: Clock;
  constructor(loans: LoanRepository, clock: Clock) { this.loans = loans; this.clock = clock; }
  borrow(member: string, title: string): Loan { return this.loans.add(member, title, addDays(this.clock.today(), 14)); }
  returnBook(id: number): number {
    const loan = this.loans.find(id);
    return Math.min(Math.max(0, daysBetween(loan.due, this.clock.today())) * 25, 500);
  }
}

class OverdueNotice {
  private readonly loans: LoanRepository;
  constructor(loans: LoanRepository) { this.loans = loans; }
  for(id: number): string {
    const loan = this.loans.find(id);
    return `${loan.member}, ${loan.title}, was due ${loan.due}`;
  }
}

// The test: a fixed clock and loans kept in memory. No database.
const clock = new FixedClock("2026-03-02");
const loans = new InMemoryLoans();
const service = new CheckoutService(loans, clock);
const loan = service.borrow("Maya", "The Lighthouse Keeper");
clock.day = addDays(clock.day, 20);
const fee = service.returnBook(loan.id);
console.log(`Returned 20 days later: late fee $${(fee / 100).toFixed(2)}, ` + (fee === 150 ? "passed" : "failed"));
console.log("Notice: " + new OverdueNotice(loans).for(loan.id));

// The app: loans kept in the library's database.
const app = new CheckoutService(new DatabaseLoans(new LibraryDatabase("riverside-db")), clock);
console.log(`App: loan ${app.borrow("Sam", "Rivers of Glass").id} is in the library database`);
```

```text
Returned 20 days later: late fee $1.50, passed
Notice: Maya, The Lighthouse Keeper, was due 2026-03-16
Connecting to riverside-db...
App: loan 1 is in the library database
```

The test makes no connection at all. The service and the notice say "add" and "find", and `DatabaseLoans` is the one class that knows the words `"loans"`, `"member"` and `"due"`. When CloudShelf arrives, the team writes one more keeper of the promise, `CloudShelfLoans`, and changes one line in the composition root. The service, the notice and every test stay as they are.

**Where the languages differ.** C#, Java and TypeScript write the promise as an interface, and Python as an abstract base class. JavaScript has neither: any object with `add` and `find` methods will do, so the comment names the promise.

## Where you've already used it

- **A list or a dictionary** is the simplest repository there is: `InMemoryLoans` is a list with the app's words on it.
- **Frameworks write repositories for you.** Here is the loan repository as each language's most common database tool writes it. These aren't run here: each needs a real database and its library. Versions checked on 2026-11-01.

```csharp
// Entity Framework Core 10: a DbContext's DbSet<Loan> already acts like a repository.
// Many teams still put it behind their own interface, so tests can hand in InMemoryLoans.
public class DatabaseLoans(LibraryContext db) : ILoanRepository
{
    public Loan Add(string member, string title, DateOnly due)
    {
        Loan loan = new Loan { Member = member, Title = title, Due = due };
        db.Loans.Add(loan);
        db.SaveChanges();
        return loan;
    }

    public Loan Find(int id) => db.Loans.Single(loan => loan.Id == id);
}
```

```java
// Spring Data JPA, with Spring Boot 4.1: you write only the interface, in the app's words,
// and Spring writes the class that keeps it, reading the method names.
import java.util.List;
import org.springframework.data.repository.CrudRepository;

public interface LoanRepository extends CrudRepository<Loan, Integer> {
    List<Loan> findByMember(String member);
}
```

```python
# SQLAlchemy 2.1: a Session talks to the database; the repository is the one class that uses it.
from sqlalchemy.orm import Session

from library import Loan


class DatabaseLoans:
    def __init__(self, session: Session):
        self.session = session

    def add(self, member, title, due):
        loan = Loan(member=member, title=title, due=due)
        self.session.add(loan)
        self.session.commit()
        return loan

    def find(self, id):
        return self.session.get(Loan, id)
```

```javascript
// Node.js's built-in SQLite (node:sqlite): Express has no database part of its own, so
// teams pick one and write a repository like this, the one class that knows the SQL.
import { DatabaseSync } from "node:sqlite";

export class DatabaseLoans {
  #db;
  constructor(file) {
    this.#db = new DatabaseSync(file);
    this.#db.exec("CREATE TABLE IF NOT EXISTS loans (id INTEGER PRIMARY KEY, member TEXT, title TEXT, due TEXT)");
  }
  add(member, title, due) {
    const result = this.#db.prepare("INSERT INTO loans (member, title, due) VALUES (?, ?, ?)").run(member, title, due);
    return { id: Number(result.lastInsertRowid), member, title, due };
  }
  find(id) {
    return this.#db.prepare("SELECT id, member, title, due FROM loans WHERE id = ?").get(id);
  }
}
```

```typescript
// TypeORM 1.1 with NestJS 12.3: TypeORM even calls its own class Repository<T>.
// Ours keeps the app's promise on top of it.
import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { LoanEntity, type Loan, type LoanRepository } from "./library";

@Injectable()
export class DatabaseLoans implements LoanRepository {
  constructor(@InjectRepository(LoanEntity) private readonly loans: Repository<LoanEntity>) {}

  async add(member: string, title: string, due: string): Promise<Loan> {
    return this.loans.save({ member, title, due });
  }

  async find(id: number): Promise<Loan> {
    return this.loans.findOneByOrFail({ id });
  }
}
```

A database tool's methods usually take time to answer, so in real code `add` and `find` are often **async** (they return a promise, or a `Task` in C#, of the loan). The pattern is the same.

## When not to use it

- **For a small script** that reads one file and prints a report. There's one place the data lives, and nothing to swap.
- **When it grows a method for every report.** `FindOverdueLoansForMembersWithFinesOver5InMarch` is a sign the repository is being asked to do a reporting tool's job. Keep it to finding and saving; give big reports a query of their own.
- **Wrapping a repository in another repository.** If your framework's tool already is one and you never swap it, a second layer only adds a jump. Many teams still add their own interface for the tests; it's a judgment call, so say why in the code review.

A repository hides *where* things are kept. The rules about them, such as the late fee, stay in the service: a repository that works out fees has started doing two jobs.

**How often you'll meet it:** every day in apps that keep data (our estimate).

## Check yourself

2 questions to try on the lesson page.

## So what

Ask for the book, not the shelf. When the service speaks only about loans, the shelves can move, a test can keep its loans in memory, and the one class that knows the database's words is the only one that changes when the database does.

## Key terms

- [Repository Pattern](https://www.ask-codey.com/glossary/repository-pattern)
- [Interface](https://www.ask-codey.com/glossary/interface-oop)
- [Dependency Inversion Principle](https://www.ask-codey.com/glossary/dependency-inversion-principle)

## Cheat sheets

- [Repository: Ask for the Book, Not the Shelf](https://www.ask-codey.com/cheat-sheets/dp-repository-cheat-sheet)

Source: https://www.ask-codey.com/lessons/dp-repository
