Programming Search⌘K

Patterncore

Repository pattern

Also called Repository.

A repository gives the domain code a collection-like interface to stored objects, such as add, get and find by criteria, and hides the database queries and the mapping behind it.

Family
architectural
Intent
Mediate between the domain and the data mapping layers using a collection-like interface for accessing domain objects.

Intent

Mediate between the domain and the data mapping layers using a collection-like interface for accessing domain objects.1 The domain code asks a repository for orders as if the orders were in a collection in memory. The repository turns each request into a query, and turns the rows into objects.

Problem

An order service ships orders, lists the orders of a customer, and cancels orders that are not paid. The first version writes SQL in each method of the service. After a year, the query for "the open orders of a customer" exists in six places, each with small differences. The service cannot be tested without a database. And a change to the tables touches the business rules.

The forces are these. The business rules should read like the business: get an order, ship it, store it. The queries should be in one place, because each query encodes a decision about the schema. The code that applies the rules should be testable without a database. And the domain objects should not know how they are stored.

Fowler's catalog describes the setting: a system with a complex domain model benefits from a layer, such as Data Mapper, that keeps the domain objects separate from the database access code. In such a system, it can be worth adding another layer of abstraction over the mapping layer, where the query construction code is concentrated.13

Solution

Define, for each kind of object that the domain code must find, an interface that looks like a collection: add an object, remove it, get it by identity, find the objects that match a criterion. Write one implementation over the database and, when tests need one, another in memory. The domain code depends on the interface only.

  domain / application code
      ship_order(orders, 1)
            |
            v
  OrderRepository (interface, in the language of the domain)
      add(order)   get(id)   by_customer(name)   update(order)
            ^                         ^
            |                         |
  SqliteOrderRepository       InMemoryOrderRepository
  SQL, rows -> Order          dict of copies
            |
            v
         database

Evans states the pattern for domain-driven design. For each type of aggregate that needs global access, create a service that can provide "the illusion of an in-memory collection of all objects of that aggregate's root type".7 It has methods to add and remove objects, and methods that select objects by criteria that mean something to domain experts. Evans limits repositories to the roots of aggregates that need direct access: an order line is reached through its order, so there is no repository for order lines.76

The repository is not the mapper. In Fowler's catalog, Repository sits over a Data Mapper, the layer that moves data between objects and tables.13 An ORM usually provides the mapper. The repository adds the vocabulary of the domain: by_customer, overdue, awaiting_payment.

The following program runs one function, ship_order, against two implementations of the same interface. One stores rows in SQLite. The other keeps copies in a dictionary. The SQL uses placeholders, never string formatting, so values from users cannot change the query.12 See SQL injection.

import sqlite3
from dataclasses import dataclass, replace
from typing import Protocol


@dataclass
class Order:
    id: int
    customer: str
    total: int
    status: str = "open"

    def ship(self) -> None:
        if self.status != "open":
            raise ValueError(f"order {self.id} is {self.status}")
        self.status = "shipped"


class OrderRepository(Protocol):
    def add(self, order: Order) -> None: ...
    def get(self, order_id: int) -> Order | None: ...
    def by_customer(self, customer: str) -> list[Order]: ...
    def update(self, order: Order) -> None: ...


class SqliteOrderRepository:
    def __init__(self, db: sqlite3.Connection) -> None:
        self._db = db
        db.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, customer TEXT, total INTEGER, status TEXT)")

    def add(self, order: Order) -> None:
        self._db.execute("INSERT INTO orders VALUES (?, ?, ?, ?)", (order.id, order.customer, order.total, order.status))

    def get(self, order_id: int) -> Order | None:
        row = self._db.execute("SELECT id, customer, total, status FROM orders WHERE id = ?", (order_id,)).fetchone()
        return Order(*row) if row else None

    def by_customer(self, customer: str) -> list[Order]:
        rows = self._db.execute("SELECT id, customer, total, status FROM orders WHERE customer = ? ORDER BY id", (customer,))
        return [Order(*row) for row in rows]

    def update(self, order: Order) -> None:
        self._db.execute("UPDATE orders SET customer = ?, total = ?, status = ? WHERE id = ?", (order.customer, order.total, order.status, order.id))


class InMemoryOrderRepository:
    def __init__(self) -> None:
        self._rows: dict[int, Order] = {}

    def add(self, order: Order) -> None:
        self._rows[order.id] = replace(order)

    def get(self, order_id: int) -> Order | None:
        row = self._rows.get(order_id)
        return replace(row) if row else None

    def by_customer(self, customer: str) -> list[Order]:
        return [replace(o) for _, o in sorted(self._rows.items()) if o.customer == customer]

    def update(self, order: Order) -> None:
        self._rows[order.id] = replace(order)


def ship_order(orders: OrderRepository, order_id: int) -> str:
    order = orders.get(order_id)
    if order is None:
        return f"order {order_id}: not found"
    order.ship()
    orders.update(order)
    return f"order {order_id} is {order.status}"


for name, repo in [("sqlite", SqliteOrderRepository(sqlite3.connect(":memory:"))), ("memory", InMemoryOrderRepository())]:
    for order in [Order(1, "ana", 30), Order(2, "bo", 12), Order(3, "ana", 5)]:
        repo.add(order)
    shipped = ship_order(repo, 1)
    ana = [(o.id, o.status) for o in repo.by_customer("ana")]
    print(f"{name}: {shipped}; ana: {ana}; {ship_order(repo, 9)}")
Output
sqlite: order 1 is shipped; ana: [(1, 'shipped'), (3, 'open')]; order 9: not found
memory: order 1 is shipped; ana: [(1, 'shipped'), (3, 'open')]; order 9: not found

Example

Each example file defines an Order with a ship method, an order repository with add, get, by_customer and update, and an in-memory implementation. The function ship_order gets an order, ships it, and stores it, and it knows only the interface. Each implementation returns copies, or immutable values, so a change reaches storage only through update, as it does with a database. The Python, JavaScript, Go, Rust and C++ files use a mutable order. The Java and C# files use an immutable record whose ship returns a changed copy.

The examples stay in memory because the standard libraries of most of these languages have no database. The Python block above shows the same interface over SQLite.

PythonGitHub
from dataclasses import dataclass, replace
from typing import Protocol


@dataclass
class Order:
    id: int
    customer: str
    total: int
    status: str = "open"

    def ship(self) -> None:
        if self.status != "open":
            raise ValueError(f"order {self.id} is {self.status}")
        self.status = "shipped"


class OrderRepository(Protocol):
    """The domain's view of storage: a collection of orders."""

    def add(self, order: Order) -> None: ...
    def get(self, order_id: int) -> Order | None: ...
    def by_customer(self, customer: str) -> list[Order]: ...
    def update(self, order: Order) -> None: ...


class InMemoryOrderRepository:
    """Stores copies, so a caller must call update, as with a database."""

    def __init__(self) -> None:
        self._rows: dict[int, Order] = {}

    def add(self, order: Order) -> None:
        if order.id in self._rows:
            raise KeyError(f"order {order.id} exists")
        self._rows[order.id] = replace(order)

    def get(self, order_id: int) -> Order | None:
        row = self._rows.get(order_id)
        return replace(row) if row else None

    def by_customer(self, customer: str) -> list[Order]:
        return [replace(o) for o in sorted(self._rows.values(), key=lambda o: o.id) if o.customer == customer]

    def update(self, order: Order) -> None:
        if order.id not in self._rows:
            raise KeyError(f"order {order.id} does not exist")
        self._rows[order.id] = replace(order)


def ship_order(orders: OrderRepository, order_id: int) -> str:
    """Application code. It knows the repository, not the storage."""
    order = orders.get(order_id)
    if order is None:
        return f"order {order_id}: not found"
    order.ship()
    orders.update(order)
    return f"order {order_id} is {order.status}"


repo = InMemoryOrderRepository()
for order in [Order(1, "ana", 30), Order(2, "bo", 12), Order(3, "ana", 5)]:
    repo.add(order)
print("ana:", ", ".join(f"order {o.id} ({o.total})" for o in repo.by_customer("ana")))
print(ship_order(repo, 1))
print(ship_order(repo, 9))
stored = repo.get(1)
print(f"stored: order {stored.id} is {stored.status}")
Output
ana: order 1 (30), order 3 (5)
order 1 is shipped
order 9: not found
stored: order 1 is shipped
  • Verdict: idiom. A Protocol states the collection-like interface, and any class with those methods is a repository. The node page runs the same ship_order against a SQLite repository.
  • The in-memory class returns copies. A caller that changes an order and forgets update sees the change lost, as it would be with a database. The node page shows what goes wrong when a fake returns live objects.
  • ship is domain logic and stays on Order. The repository has no business rules: it stores and finds.
#include <iostream>
#include <map>
#include <optional>
#include <stdexcept>
#include <string>
#include <vector>

enum class Status { open, shipped };

const char* name(Status s) { return s == Status::open ? "open" : "shipped"; }

struct Order {
    int id;
    std::string customer;
    int total;
    Status status = Status::open;

    void ship() {
        if (status != Status::open)
            throw std::logic_error("order " + std::to_string(id) + " is " + name(status));
        status = Status::shipped;
    }
};

class OrderRepository {
public:
    virtual ~OrderRepository() = default;
    virtual void add(const Order& order) = 0;
    virtual std::optional<Order> get(int id) const = 0;
    virtual std::vector<Order> by_customer(const std::string& customer) const = 0;
    virtual void update(const Order& order) = 0;
};

// Returns values, not references, so callers cannot change stored rows.
class InMemoryOrderRepository : public OrderRepository {
public:
    void add(const Order& order) override {
        if (!rows_.emplace(order.id, order).second)
            throw std::invalid_argument("order " + std::to_string(order.id) + " exists");
    }
    std::optional<Order> get(int id) const override {
        auto it = rows_.find(id);
        if (it == rows_.end()) return std::nullopt;
        return it->second;
    }
    std::vector<Order> by_customer(const std::string& customer) const override {
        std::vector<Order> out;
        for (const auto& [id, o] : rows_)
            if (o.customer == customer) out.push_back(o);
        return out;
    }
    void update(const Order& order) override {
        auto it = rows_.find(order.id);
        if (it == rows_.end()) throw std::out_of_range("order " + std::to_string(order.id));
        it->second = order;
    }

private:
    std::map<int, Order> rows_;
};

std::string ship_order(OrderRepository& orders, int id) {
    auto order = orders.get(id);
    if (!order) return "order " + std::to_string(id) + ": not found";
    order->ship();
    orders.update(*order);
    return "order " + std::to_string(id) + " is " + name(order->status);
}

int main() {
    InMemoryOrderRepository repo;
    repo.add({1, "ana", 30});
    repo.add({2, "bo", 12});
    repo.add({3, "ana", 5});
    std::cout << "ana: ";
    const char* sep = "";
    for (const auto& o : repo.by_customer("ana")) {
        std::cout << sep << "order " << o.id << " (" << o.total << ")";
        sep = ", ";
    }
    std::cout << "\n" << ship_order(repo, 1) << "\n" << ship_order(repo, 9) << "\n";
    auto stored = repo.get(1);
    std::cout << "stored: order " << stored->id << " is " << name(stored->status) << "\n";
}
Output
ana: order 1 (30), order 3 (5)
order 1 is shipped
order 9: not found
stored: order 1 is shipped
  • Verdict: idiom. An abstract class gives the contract, and std::optional<Order> makes "not found" part of the return type.
  • get returns an Order by value. A version that returns Order& or Order* into the map would let callers change stored rows without update, and the pointer would dangle if the map erased the row.
  • std::map keeps the keys sorted, so by_customer gives orders sorted by id.
JavaGitHub
import java.util.List;
import java.util.Optional;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class Main {
    enum Status { OPEN, SHIPPED }

    // An immutable domain object: ship() returns the changed order.
    record Order(int id, String customer, int total, Status status) {
        Order(int id, String customer, int total) { this(id, customer, total, Status.OPEN); }

        Order ship() {
            if (status != Status.OPEN) throw new IllegalStateException("order " + id + " is " + status);
            return new Order(id, customer, total, Status.SHIPPED);
        }
    }

    interface OrderRepository {
        void add(Order order);
        Optional<Order> get(int id);
        List<Order> byCustomer(String customer);
        void update(Order order);
    }

    static final class InMemoryOrderRepository implements OrderRepository {
        private final TreeMap<Integer, Order> rows = new TreeMap<>();

        public void add(Order order) {
            if (rows.putIfAbsent(order.id(), order) != null)
                throw new IllegalArgumentException("order " + order.id() + " exists");
        }
        public Optional<Order> get(int id) { return Optional.ofNullable(rows.get(id)); }
        public List<Order> byCustomer(String customer) {
            return rows.values().stream().filter(o -> o.customer().equals(customer)).toList();
        }
        public void update(Order order) {
            if (rows.replace(order.id(), order) == null)
                throw new IllegalArgumentException("order " + order.id() + " does not exist");
        }
    }

    static String shipOrder(OrderRepository orders, int id) {
        return orders.get(id)
                .map(order -> {
                    Order shipped = order.ship();
                    orders.update(shipped);
                    return "order " + id + " is " + shipped.status().name().toLowerCase();
                })
                .orElse("order " + id + ": not found");
    }

    public static void main(String[] args) {
        OrderRepository repo = new InMemoryOrderRepository();
        repo.add(new Order(1, "ana", 30));
        repo.add(new Order(2, "bo", 12));
        repo.add(new Order(3, "ana", 5));
        System.out.println("ana: " + repo.byCustomer("ana").stream()
                .map(o -> "order " + o.id() + " (" + o.total() + ")")
                .collect(Collectors.joining(", ")));
        System.out.println(shipOrder(repo, 1));
        System.out.println(shipOrder(repo, 9));
        Order stored = repo.get(1).orElseThrow();
        System.out.println("stored: order " + stored.id() + " is " + stored.status().name().toLowerCase());
    }
}
Output
ana: order 1 (30), order 3 (5)
order 1 is shipped
order 9: not found
stored: order 1 is shipped
  • Verdict: idiom. An interface gives the collection-like contract, and Optional makes "not found" part of the return type of get.
  • Order is a record, so it is immutable. The repository can store the object itself, because no caller can change it. A change makes another record, and the caller must pass it to update.
  • TreeMap keeps the orders sorted by id, so byCustomer returns them in a stable order.
  • Spring Data generates an implementation of an interface like this one from the names of its methods. That library is not part of the JDK, so this program writes the implementation by hand.
var repo = new InMemoryOrderRepository();
repo.Add(new Order(1, "ana", 30));
repo.Add(new Order(2, "bo", 12));
repo.Add(new Order(3, "ana", 5));
Console.WriteLine("ana: " + string.Join(", ", repo.ByCustomer("ana").Select(o => $"order {o.Id} ({o.Total})")));
Console.WriteLine(ShipOrder(repo, 1));
Console.WriteLine(ShipOrder(repo, 9));
var stored = repo.Get(1)!;
Console.WriteLine($"stored: order {stored.Id} is {stored.Status.ToString().ToLowerInvariant()}");

static string ShipOrder(IOrderRepository orders, int id)
{
    if (orders.Get(id) is not { } order) return $"order {id}: not found";
    var shipped = order.Ship();
    orders.Update(shipped);
    return $"order {id} is {shipped.Status.ToString().ToLowerInvariant()}";
}

enum Status { Open, Shipped }

record Order(int Id, string Customer, int Total, Status Status = Status.Open)
{
    public Order Ship() => Status == Status.Open
        ? this with { Status = Status.Shipped }
        : throw new InvalidOperationException($"order {Id} is {Status}");
}

interface IOrderRepository
{
    void Add(Order order);
    Order? Get(int id);
    IReadOnlyList<Order> ByCustomer(string customer);
    void Update(Order order);
}

sealed class InMemoryOrderRepository : IOrderRepository
{
    private readonly SortedDictionary<int, Order> _rows = new();

    public void Add(Order order)
    {
        if (!_rows.TryAdd(order.Id, order)) throw new ArgumentException($"order {order.Id} exists");
    }

    public Order? Get(int id) => _rows.GetValueOrDefault(id);

    // A list, not an IQueryable: the query stays inside the repository.
    public IReadOnlyList<Order> ByCustomer(string customer) =>
        _rows.Values.Where(o => o.Customer == customer).ToList();

    public void Update(Order order)
    {
        if (!_rows.ContainsKey(order.Id)) throw new KeyNotFoundException($"order {order.Id}");
        _rows[order.Id] = order;
    }
}
Output
ana: order 1 (30), order 3 (5)
order 1 is shipped
order 9: not found
stored: order 1 is shipped
  • Verdict: idiom. An interface gives the contract, and an immutable record is the domain object. with makes the changed copy in Ship.
  • ByCustomer returns a materialized list. A repository that returns IQueryable<Order> lets each caller add query operators, so the queries leave the repository, and a test double cannot replace them. The Entity Framework Core documentation on testing says to return IEnumerable for this reason.
  • With Entity Framework Core, DbContext already combines a unit of work and repositories, and DbSet<Order> is a collection of orders. The node page discusses when a repository on top of it adds nothing.
JavaScriptGitHub
class Order {
  constructor(id, customer, total, status = "open") {
    Object.assign(this, { id, customer, total, status });
  }
  ship() {
    if (this.status !== "open") throw new Error(`order ${this.id} is ${this.status}`);
    this.status = "shipped";
  }
}

// Stores plain records and rebuilds an Order on each read, as a database would.
class InMemoryOrderRepository {
  #rows = new Map();

  add(order) {
    if (this.#rows.has(order.id)) throw new Error(`order ${order.id} exists`);
    this.#rows.set(order.id, { ...order });
  }
  get(id) {
    const row = this.#rows.get(id);
    return row ? Object.assign(new Order(), row) : undefined;
  }
  byCustomer(customer) {
    return [...this.#rows.keys()]
      .sort((a, b) => a - b)
      .map((id) => this.get(id))
      .filter((o) => o.customer === customer);
  }
  update(order) {
    if (!this.#rows.has(order.id)) throw new Error(`order ${order.id} does not exist`);
    this.#rows.set(order.id, { ...order });
  }
}

// Application code. It only needs an object with get and update.
function shipOrder(orders, id) {
  const order = orders.get(id);
  if (!order) return `order ${id}: not found`;
  order.ship();
  orders.update(order);
  return `order ${id} is ${order.status}`;
}

const repo = new InMemoryOrderRepository();
[new Order(1, "ana", 30), new Order(2, "bo", 12), new Order(3, "ana", 5)].forEach((o) => repo.add(o));
console.log("ana:", repo.byCustomer("ana").map((o) => `order ${o.id} (${o.total})`).join(", "));
console.log(shipOrder(repo, 1));
console.log(shipOrder(repo, 9));
const stored = repo.get(1);
console.log(`stored: order ${stored.id} is ${stored.status}`);
Output
ana: order 1 (30), order 3 (5)
order 1 is shipped
order 9: not found
stored: order 1 is shipped
  • Verdict: idiom. JavaScript has no interfaces, so the repository is any object with add, get, byCustomer and update. shipOrder works with an in-memory class, a SQL class or a class over an HTTP API.
  • The repository stores a spread copy of the fields and builds a fresh Order on each read. Callers cannot change a stored order without update.
  • get returns undefined for a missing order, so the caller must check before it calls ship.
TypeScriptGitHub
type Status = "open" | "shipped";

class Order {
  readonly id: number;
  readonly customer: string;
  readonly total: number;
  status: Status;

  constructor(id: number, customer: string, total: number, status: Status = "open") {
    this.id = id;
    this.customer = customer;
    this.total = total;
    this.status = status;
  }

  ship(): void {
    if (this.status !== "open") throw new Error(`order ${this.id} is ${this.status}`);
    this.status = "shipped";
  }
}

// The domain declares the interface. The storage layer implements it.
interface OrderRepository {
  add(order: Order): void;
  get(id: number): Order | undefined;
  byCustomer(customer: string): Order[];
  update(order: Order): void;
}

const copy = (o: Order): Order => new Order(o.id, o.customer, o.total, o.status);

class InMemoryOrderRepository implements OrderRepository {
  readonly #rows = new Map<number, Order>();

  add(order: Order): void {
    if (this.#rows.has(order.id)) throw new Error(`order ${order.id} exists`);
    this.#rows.set(order.id, copy(order));
  }
  get(id: number): Order | undefined {
    const row = this.#rows.get(id);
    return row && copy(row);
  }
  byCustomer(customer: string): Order[] {
    return [...this.#rows.values()]
      .filter((o) => o.customer === customer)
      .sort((a, b) => a.id - b.id)
      .map(copy);
  }
  update(order: Order): void {
    if (!this.#rows.has(order.id)) throw new Error(`order ${order.id} does not exist`);
    this.#rows.set(order.id, copy(order));
  }
}

function shipOrder(orders: OrderRepository, id: number): string {
  const order = orders.get(id);
  if (order === undefined) return `order ${id}: not found`;
  order.ship();
  orders.update(order);
  return `order ${id} is ${order.status}`;
}

const repo: OrderRepository = new InMemoryOrderRepository();
for (const o of [new Order(1, "ana", 30), new Order(2, "bo", 12), new Order(3, "ana", 5)]) repo.add(o);
console.log("ana:", repo.byCustomer("ana").map((o) => `order ${o.id} (${o.total})`).join(", "));
console.log(shipOrder(repo, 1));
console.log(shipOrder(repo, 9));
const stored = repo.get(1)!;
console.log(`stored: order ${stored.id} is ${stored.status}`);
Output
ana: order 1 (30), order 3 (5)
order 1 is shipped
order 9: not found
stored: order 1 is shipped
  • Verdict: idiom. An interface states the collection-like contract in the language of the domain. shipOrder depends on the interface only.
  • get returns Order | undefined. With strictNullChecks, the compiler rejects order.ship() before the check.
  • Status is a union of two string literals, so the compiler rejects a typo such as "shiped" in an assignment to status.
package main

import (
	"errors"
	"fmt"
	"slices"
	"strings"
)

type Order struct {
	ID       int
	Customer string
	Total    int
	Status   string
}

func (o *Order) Ship() error {
	if o.Status != "open" {
		return fmt.Errorf("order %d is %s", o.ID, o.Status)
	}
	o.Status = "shipped"
	return nil
}

var ErrNotFound = errors.New("not found")

// OrderRepository is declared by the code that uses it.
type OrderRepository interface {
	Add(o Order) error
	Get(id int) (Order, error)
	ByCustomer(customer string) []Order
	Update(o Order) error
}

// MemoryOrders stores Order values, so every Get returns a copy.
type MemoryOrders struct{ rows map[int]Order }

func NewMemoryOrders() *MemoryOrders { return &MemoryOrders{rows: map[int]Order{}} }

func (m *MemoryOrders) Add(o Order) error {
	if _, ok := m.rows[o.ID]; ok {
		return fmt.Errorf("order %d exists", o.ID)
	}
	m.rows[o.ID] = o
	return nil
}

func (m *MemoryOrders) Get(id int) (Order, error) {
	o, ok := m.rows[id]
	if !ok {
		return Order{}, ErrNotFound
	}
	return o, nil
}

func (m *MemoryOrders) ByCustomer(customer string) []Order {
	var out []Order
	for _, o := range m.rows {
		if o.Customer == customer {
			out = append(out, o)
		}
	}
	slices.SortFunc(out, func(a, b Order) int { return a.ID - b.ID })
	return out
}

func (m *MemoryOrders) Update(o Order) error {
	if _, ok := m.rows[o.ID]; !ok {
		return ErrNotFound
	}
	m.rows[o.ID] = o
	return nil
}

func ShipOrder(orders OrderRepository, id int) string {
	o, err := orders.Get(id)
	if errors.Is(err, ErrNotFound) {
		return fmt.Sprintf("order %d: not found", id)
	}
	if err := o.Ship(); err != nil {
		return err.Error()
	}
	if err := orders.Update(o); err != nil {
		return err.Error()
	}
	return fmt.Sprintf("order %d is %s", id, o.Status)
}

func main() {
	var repo OrderRepository = NewMemoryOrders()
	for _, o := range []Order{{1, "ana", 30, "open"}, {2, "bo", 12, "open"}, {3, "ana", 5, "open"}} {
		repo.Add(o)
	}
	var parts []string
	for _, o := range repo.ByCustomer("ana") {
		parts = append(parts, fmt.Sprintf("order %d (%d)", o.ID, o.Total))
	}
	fmt.Println("ana:", strings.Join(parts, ", "))
	fmt.Println(ShipOrder(repo, 1))
	fmt.Println(ShipOrder(repo, 9))
	stored, _ := repo.Get(1)
	fmt.Printf("stored: order %d is %s\n", stored.ID, stored.Status)
}
Output
ana: order 1 (30), order 3 (5)
order 1 is shipped
order 9: not found
stored: order 1 is shipped
  • Verdict: idiom. An interface lists the operations, and a sentinel error ErrNotFound lets callers tell "not found" from a failure of the storage.
  • The map holds Order values, not pointers. Get returns a copy, so a change to an order is lost unless the caller passes it to Update, as with a database.
  • The order of a Go map is not specified, so ByCustomer sorts its result by id.
  • database/sql gives the SQL side of a Go repository: a second type with the same methods would hold a *sql.DB. The standard library has no driver for a database, so this program stays in memory.
RustGitHub
use std::collections::BTreeMap;

#[derive(Clone, Debug, PartialEq)]
enum Status {
    Open,
    Shipped,
}

#[derive(Clone, Debug)]
struct Order {
    id: u32,
    customer: String,
    total: u32,
    status: Status,
}

impl Order {
    fn new(id: u32, customer: &str, total: u32) -> Self {
        Order { id, customer: customer.into(), total, status: Status::Open }
    }

    fn ship(&mut self) -> Result<(), String> {
        if self.status != Status::Open {
            return Err(format!("order {} is {:?}", self.id, self.status));
        }
        self.status = Status::Shipped;
        Ok(())
    }
}

trait OrderRepository {
    fn add(&mut self, order: Order) -> Result<(), String>;
    fn get(&self, id: u32) -> Option<Order>;
    fn by_customer(&self, customer: &str) -> Vec<Order>;
    fn update(&mut self, order: Order) -> Result<(), String>;
}

#[derive(Default)]
struct InMemoryOrders {
    rows: BTreeMap<u32, Order>,
}

impl OrderRepository for InMemoryOrders {
    fn add(&mut self, order: Order) -> Result<(), String> {
        if self.rows.contains_key(&order.id) {
            return Err(format!("order {} exists", order.id));
        }
        self.rows.insert(order.id, order);
        Ok(())
    }

    fn get(&self, id: u32) -> Option<Order> {
        self.rows.get(&id).cloned()
    }

    fn by_customer(&self, customer: &str) -> Vec<Order> {
        self.rows.values().filter(|o| o.customer == customer).cloned().collect()
    }

    fn update(&mut self, order: Order) -> Result<(), String> {
        match self.rows.get_mut(&order.id) {
            Some(row) => {
                *row = order;
                Ok(())
            }
            None => Err(format!("order {} does not exist", order.id)),
        }
    }
}

fn ship_order(orders: &mut impl OrderRepository, id: u32) -> String {
    let Some(mut order) = orders.get(id) else {
        return format!("order {id}: not found");
    };
    if let Err(e) = order.ship().and_then(|()| orders.update(order.clone())) {
        return e;
    }
    format!("order {id} is {}", format!("{:?}", order.status).to_lowercase())
}

fn main() {
    let mut repo = InMemoryOrders::default();
    for o in [Order::new(1, "ana", 30), Order::new(2, "bo", 12), Order::new(3, "ana", 5)] {
        repo.add(o).unwrap();
    }
    let ana: Vec<String> = repo
        .by_customer("ana")
        .iter()
        .map(|o| format!("order {} ({})", o.id, o.total))
        .collect();
    println!("ana: {}", ana.join(", "));
    println!("{}", ship_order(&mut repo, 1));
    println!("{}", ship_order(&mut repo, 9));
    let stored = repo.get(1).unwrap();
    println!("stored: order {} is {}", stored.id, format!("{:?}", stored.status).to_lowercase());
}
Output
ana: order 1 (30), order 3 (5)
order 1 is shipped
order 9: not found
stored: order 1 is shipped
  • Verdict: idiom. A trait gives the collection-like contract. get returns Option<Order>, so the compiler makes the caller handle a missing order.
  • get returns an owned clone. The repository keeps the only stored copy, and the borrow rules make the caller give a changed order back through update, which takes &mut self.
  • BTreeMap keeps the keys in order, so by_customer returns the orders sorted by id with no extra sort.

Consequences

Benefits.

  • The queries are in one place. The query for "the orders of a customer" exists once, in the repository, and has a name.1
  • The domain code reads like the domain. orders.by_customer("ana") states the intent. The SQL is behind it.
  • The domain does not depend on storage. The dependency runs one way: the mapping layer knows the domain, and the domain knows only the interface.1 With Dependency injection, the application receives a repository and does not choose it.
  • A test can use a fake. The application logic runs against an in-memory implementation, fast and with no database.

Liabilities.

A fake is not the database. An in-memory repository does not run the constraints, the transactions or the collation of the real database. The Entity Framework Core documentation recommends a repository layer for a reliable test double. In the same section, it says that the layer has a significant cost to build and maintain, and that tests against the real database are still likely to be needed for the queries in the repository.9 It also warns that SQLite and other substitutes behave differently from the production database, for example in case sensitivity.9

A subtler gap is object identity. An in-memory fake that returns the stored object, not a copy, makes a missing update call invisible:

This code runs but gives a wrong answer on purpose.

import sqlite3
from dataclasses import dataclass


@dataclass
class Order:
    id: int
    status: str = "open"


class FakeOrders:
    def __init__(self):
        self.rows = {}

    def add(self, order):
        self.rows[order.id] = order

    def get(self, order_id):
        return self.rows[order_id]  # the stored object itself

    def update(self, order):
        self.rows[order.id] = order


class SqliteOrders:
    def __init__(self):
        self.db = sqlite3.connect(":memory:")
        self.db.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, status TEXT)")

    def add(self, order):
        self.db.execute("INSERT INTO orders VALUES (?, ?)", (order.id, order.status))

    def get(self, order_id):
        return Order(*self.db.execute("SELECT id, status FROM orders WHERE id = ?", (order_id,)).fetchone())

    def update(self, order):
        self.db.execute("UPDATE orders SET status = ? WHERE id = ?", (order.status, order.id))


def ship_order(orders, order_id):
    order = orders.get(order_id)
    order.status = "shipped"
    # bug: no orders.update(order)


for repo in [FakeOrders(), SqliteOrders()]:
    repo.add(Order(1))
    ship_order(repo, 1)
    print(f"{type(repo).__name__}: {repo.get(1).status}")
Output
FakeOrders: shipped
SqliteOrders: open

The test with the fake passes, and production loses the change. The fakes in the example files return copies for this reason. The other answer is a Unit of Work, which tracks the objects that a business transaction has read and changed, and writes the changes at the end.5 With a unit of work, the repository can behave like a real collection with no update method, and both the fake and the real store must then track changes.

Collection semantics leak. A repository looks like a collection, but each call can be a round trip to a database. A loop that calls get for each of a thousand ids makes a thousand queries. The interface must offer the queries that the domain needs in bulk.

The interface can become a second query language. A generic repository with a find(predicate) method, or one that returns a query object that callers can extend, moves the queries back into the callers. The EF Core documentation says that a repository used as a test double must return IEnumerable, not IQueryable, because the query operators that a caller adds to an IQueryable cannot be stubbed out.9

When not to use it

Over an ORM that already gives the collection. EF Core describes DbContext as a combination of the Unit of Work and Repository patterns.8 Django gives each model a Manager, "the interface through which database query operations are provided to Django models".10 Spring Data generates repository implementations from interfaces.11 A class OrderRepository whose methods each call one method of DbSet<Order> adds a layer, a test double and a place for bugs, and it hides nothing. Write your own repository over an ORM when it adds something: names from the domain for the queries, a boundary that keeps ORM types out of the domain layer, or a seam for tests that need no database.

With Active Record. In Active Record, an object wraps a row of a table and carries both the data access and the domain logic.4 The class is its own repository: Order.find(1). A repository on top of it fights the design of the framework. Choose one or the other.

In a small application with a thin domain. An application that reads a form and writes a row has little domain logic to protect. A query in the request handler is easier to follow than three layers.

As a generic repository for every type. An interface Repository<T> with get, add, find(predicate) for every table gives no names from the domain and lets callers build any query. Evans's version has one repository for each aggregate root, with methods for the queries that the domain needs.7

Data Mapper. The layer of mappers that moves data between objects and the database while it keeps them independent of each other.3 A repository sits on top of it and gives it a collection-like interface.1

Unit of Work. Tracks the changed objects of a business transaction and writes them together.5 A repository gives access to objects. A unit of work decides when the changes reach the database. DbContext combines the two.8

Active Record. The alternative design, where the domain object loads and saves itself.4

Facade. A repository is a facade over the mapper, the connection and the query language, with an interface in the terms of the domain. See Facade pattern.

Proxy. Evans allows a repository to return proxies that give the illusion of fully loaded aggregates and load them lazily.7 See Proxy pattern.

Dependency injection. The application receives a repository through its constructor, so a test can pass the in-memory implementation. See Dependency injection.

Iterator. A query that returns many objects can return an iterator that fetches rows in batches, instead of a list. See Iterator pattern.

Known uses

  • Spring Data: CrudRepository.java at 3.4.0 is the generic interface for create, read, update and delete operations on a repository for one type, with save and findById. Applications extend it with their own interface, and the library generates the implementation.1311
  • Django: BaseManager.get_queryset in manager.py at 5.2 returns a QuerySet for the model, and the docstring says that subclasses can override it to change the behaviour of the manager. A custom manager with named query methods is the Django form of a repository.1410

References

  1. Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Repository (by Edward Hieatt and Rob Mee), pattern summary; the book's Chapter 13
  2. Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 13, Repository; Chapter 10, Data Mapper and Active Record; Chapter 11, Unit of Work
  3. Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Data Mapper, pattern summary; the book's Chapter 10
  4. Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Active Record, pattern summary; the book's Chapter 10
  5. Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Unit of Work, pattern summary; the book's Chapter 11
  6. Eric Evans, Domain-Driven Design, Tackling Complexity in the Heart of Software, Addison-Wesley, 2003, Part II, The Building Blocks of a Model-Driven Design; Chapter 6, The Life Cycle of a Domain Object, Repositories
  7. Eric Evans, Domain-Driven Design Reference, Definitions and Pattern Summaries, 2015 (CC BY 4.0), Part II, Building Blocks of a Model-Driven Design, Repositories
  8. Entity Framework Core API, DbContext Class, class remarks
  9. Entity Framework Core, Choosing a testing strategy, Repository pattern
  10. Django 5.2 documentation, Managers, Managers, first paragraph
  11. Spring Data Commons reference, Core concepts, first section
  12. The Python Standard Library, sqlite3, Python 3.14, How to use placeholders to bind values in SQL queries
  13. Spring Data Commons 3.4.0 source, CrudRepository.java, interface CrudRepository, lines 22 to 66
  14. Django 5.2 source, django/db/models/manager.py, BaseManager.get_queryset and class Manager, lines 150 to 177

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/QP7VME/text.yaml