Show contents
Chapter 6 of 7 · 30 min
Final project: a layered booking service
By the end of this chapter, you'll be able to
- Separate domain, service and storage in a layered architecture
- Define a port with Protocol and implement it with several adapters
- Inject the storage dependency to make the service testable
- Validate the domain's invariants as soon as objects are created
Step 1: the layers
A layered architecture shares out the responsibilities:
- the domain contains the business objects and rules (a
Bookingand its overlap rule). It imports no file, no database, no display; - the service contains the use cases ("book a room", "show the schedule"). It uses storage through a port, an interface described by a
Protocol; - the adapters implement this port: in memory for tests, JSON today, a database tomorrow.
Dependencies always point towards the domain: storage depends on the domain, never the other way round.
The same service works with any adapter: you choose which one in a single place.
Text description of the animation
- A user asks for the Baobab room from 10 am to 11 am.
- The domain creates the object and checks its invariants: the end is indeed after the start.
- The service gets the existing bookings through the port, without knowing where they're stored.
- An existing booking overlaps the request: the service refuses, nothing is saved.
- The same service works with any adapter: you choose which one in a single place.
Step 2: the program
import json
from dataclasses import dataclass, asdict
from datetime import datetime
from pathlib import Path
from typing import Protocol
# --- Domain: the rules, with no file or display --------------------------
@dataclass(frozen=True)
class Booking:
room: str
start: datetime
end: datetime
by: str
def __post_init__(self):
if self.end <= self.start:
raise ValueError("the end must come after the start")
def overlaps(self, other: "Booking") -> bool:
return self.room == other.room and self.start < other.end and other.start < self.end
# --- Port: what the service needs in order to store ----------------------
class Repository(Protocol):
def all(self) -> list[Booking]: ...
def add(self, b: Booking) -> None: ...
# --- Adapters: two ways of storing ---------------------------------------
class MemoryRepository:
def __init__(self) -> None:
self._data: list[Booking] = []
def all(self) -> list[Booking]:
return list(self._data)
def add(self, b: Booking) -> None:
self._data.append(b)
class JsonRepository:
def __init__(self, path: Path) -> None:
self.path = path
def all(self) -> list[Booking]:
if not self.path.exists():
return []
raw = json.loads(self.path.read_text(encoding="utf-8"))
return [Booking(d["room"], datetime.fromisoformat(d["start"]), datetime.fromisoformat(d["end"]), d["by"]) for d in raw]
def add(self, b: Booking) -> None:
data = [asdict(x) | {"start": x.start.isoformat(), "end": x.end.isoformat()} for x in self.all() + [b]]
self.path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
# --- Service: the use cases, which only know the port --------------------
class BookingService:
def __init__(self, repository: Repository) -> None:
self.repository = repository
def book(self, room: str, start: str, end: str, by: str) -> Booking:
new = Booking(room, datetime.fromisoformat(start), datetime.fromisoformat(end), by)
conflict = next((b for b in self.repository.all() if b.overlaps(new)), None)
if conflict:
raise ValueError(f"{room} already booked by {conflict.by} until {conflict.end:%H:%M}")
self.repository.add(new)
return new
def schedule(self, room: str) -> list[str]:
return [f"{b.start:%H:%M}-{b.end:%H:%M} {b.by}" for b in sorted(self.repository.all(), key=lambda b: b.start) if b.room == room]
# --- Usage: the adapter is chosen in a single place ----------------------
file = Path("bookings.json")
file.unlink(missing_ok=True)
service = BookingService(JsonRepository(file))
requests = [
("Baobab", "2026-11-20T09:00", "2026-11-20T10:30", "Product team"),
("Baobab", "2026-11-20T10:00", "2026-11-20T11:00", "Management"),
("Baobab", "2026-11-20T10:30", "2026-11-20T12:00", "Training"),
("Kapok", "2026-11-20T09:00", "2026-11-20T08:00", "Support"),
]
for r in requests:
try:
service.book(*r)
except ValueError as error:
print("Refused:", error)
print(BookingService(JsonRepository(file)).schedule("Baobab"))
Refused: Baobab already booked by Product team until 10:30
Refused: the end must come after the start
['09:00-10:30 Product team', '10:30-12:00 Training']
The choices that matter:
- Invariants in the domain.
__post_init__runs right after a dataclass's constructor: an inconsistentBookingcan't even exist. - A rule that can be tested on its own. Two slots overlap if each starts before the other ends. Back-to-back slots (ending and starting at 10:30) are accepted.
- Dependency injection. The service receives its repository in its constructor instead of creating it itself. The adapter is chosen in a single place, at the very bottom.
asdict(x) | {...}merges two dictionaries (Python 3.9+): the dates are replaced by their ISO text, which JSON can store.f"{date:%H:%M}"formats a date in an f-string.- The last line creates a new service on the same file: the schedule read back proves the data was really saved.
Step 3: the tests, with no file
Thanks to the port, the tests use MemoryRepository: no file, no clean-up, a fresh state per test.
from dataclasses import dataclass
from datetime import datetime
@dataclass(frozen=True)
class Booking:
room: str
start: datetime
end: datetime
by: str
def overlaps(self, other):
return self.room == other.room and self.start < other.end and other.start < self.end
class MemoryRepository:
def __init__(self):
self._data = []
def all(self):
return list(self._data)
def add(self, b):
self._data.append(b)
class BookingService:
def __init__(self, repository):
self.repository = repository
def book(self, room, start, end, by):
new = Booking(room, datetime.fromisoformat(start), datetime.fromisoformat(end), by)
if any(b.overlaps(new) for b in self.repository.all()):
raise ValueError("conflict")
self.repository.add(new)
return new
def new_service():
return BookingService(MemoryRepository())
def test_back_to_back_slots_accepted():
s = new_service()
s.book("A", "2026-11-20T09:00", "2026-11-20T10:00", "x")
s.book("A", "2026-11-20T10:00", "2026-11-20T11:00", "y")
assert len(s.repository.all()) == 2
def test_overlap_refused_without_effect():
s = new_service()
s.book("A", "2026-11-20T09:00", "2026-11-20T10:00", "x")
try:
s.book("A", "2026-11-20T09:30", "2026-11-20T10:30", "y")
raise AssertionError("the overlap should have been refused")
except ValueError:
pass
assert len(s.repository.all()) == 1
def test_other_room_independent():
s = new_service()
s.book("A", "2026-11-20T09:00", "2026-11-20T10:00", "x")
s.book("B", "2026-11-20T09:00", "2026-11-20T10:00", "y")
assert len(s.repository.all()) == 2
for t in (test_back_to_back_slots_accepted, test_overlap_refused_without_effect, test_other_room_independent):
t()
print("OK", t.__name__)
OK test_back_to_back_slots_accepted
OK test_overlap_refused_without_effect
OK test_other_room_independent
To keep the example short, this copy lightens the domain (no __post_init__). In your project, these tests import the real classes from src/, with pytest fixtures, and a separate test checks JsonRepository in a temporary folder (pytest's tmp_path fixture).
Your turn
Project: cancellation and occupancy ratePython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Worked exercise
Worked exercise: an adapter that counts
Write an adapter CountingRepository that wraps another repository (any one that respects the port) and counts how many times all() and add() are called, delegating the real work to the wrapped repository. Use it to check that book reads the bookings once and adds exactly one when everything goes well.
Hint 1
Hint 2
Show the solution and common mistakes
from datetime import datetime
class MemoryRepository:
def __init__(self):
self._data = []
def all(self):
return list(self._data)
def add(self, b):
self._data.append(b)
class CountingRepository:
def __init__(self, inner):
self.inner = inner
self.reads = 0
self.writes = 0
def all(self):
self.reads += 1
return self.inner.all()
def add(self, b):
self.writes += 1
self.inner.add(b)
def book(repository, room, start, end):
new = (room, datetime.fromisoformat(start), datetime.fromisoformat(end))
for r, s, e in repository.all():
if r == room and s < new[2] and new[1] < e:
raise ValueError("conflict")
repository.add(new)
counter = CountingRepository(MemoryRepository())
book(counter, "Baobab", "2026-11-20T09:00", "2026-11-20T10:00")
print(counter.reads, counter.writes)
try:
book(counter, "Baobab", "2026-11-20T09:30", "2026-11-20T10:30")
except ValueError:
pass
print(counter.reads, counter.writes)
1 1
2 1
The service sees no difference: CountingRepository respects the same port. This way you can add a cache, logs or measurements around any storage, without touching either the service or the storage.
Common mistakes:
- Making
CountingRepositoryinherit fromMemoryRepository: it would then only work with that particular storage, whereas the wrapper works with all of them. - Counting in the service rather than in the adapter: that mixes a technical concern (measurement) with the business rules.
Summary
- 1The domain carries the rules and depends on nothing; storage depends on the domain, never the other way round.
- 2A port (Protocol) describes what the service needs; adapters implement it.
- 3Dependency injection chooses the adapter in a single place.
- 4Invariants checked at creation stop inconsistent objects from existing.
- 5Thanks to the port, tests use an in-memory repository: fast and with no file.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.