Show contents
Chapter 6 of 7 · 25 min
Project: a booking system
By the end of this chapter, you'll be able to
- Model a domain with immutable dataclasses
- Isolate business rules in a service that receives its dependencies
- Correctly detect whether two slots overlap
- Protect the rules with unit tests
The architecture
Each rule is checked by a test, with no network or database.
Text description of the animation
- Simple, immutable objects describe the domain.
- The service checks opening hours, duration and conflicts.
- It reads and saves through an interface: memory today, a database tomorrow.
- It publishes an event; sending messages is the subscribers' business.
- Each rule is checked by a test, with no network or database.
The complete system
Hours are integers (9 means 9 am) to keep the example readable. A real system would use full dates and times, with their time zone.
from dataclasses import dataclass
@dataclass(frozen=True)
class Slot:
start: int
end: int
def overlaps(self, other):
return self.start < other.end and other.start < self.end
@dataclass(frozen=True)
class Booking:
room: str
slot: Slot
member: str
class MemoryRepository:
def __init__(self):
self.bookings = []
def bookings_for(self, room):
return [b for b in self.bookings if b.room == room]
def add(self, booking):
self.bookings.append(booking)
class BookingService:
OPENING, CLOSING, MAX_DURATION = 8, 20, 2
def __init__(self, repository, publish):
self.repository = repository
self.publish = publish
def book(self, room, slot, member):
if slot.start < self.OPENING or slot.end > self.CLOSING:
raise ValueError("outside opening hours (8 am - 8 pm)")
if not 0 < slot.end - slot.start <= self.MAX_DURATION:
raise ValueError(f"invalid duration: 1 to {self.MAX_DURATION} h")
for b in self.repository.bookings_for(room):
if b.slot.overlaps(slot):
raise ValueError(f"{room} already booked from {b.slot.start} to {b.slot.end}")
booking = Booking(room, slot, member)
self.repository.add(booking)
self.publish("booking_created", booking)
return booking
notifications = []
service = BookingService(MemoryRepository(), lambda event, b: notifications.append(f"{b.member}: {b.room}, {b.slot.start}-{b.slot.end}"))
requests = [("Baobab", Slot(9, 11), "Awa"), ("Baobab", Slot(10, 12), "Kofi"),
("Baobab", Slot(11, 13), "Kofi"), ("Kapok", Slot(18, 21), "Lina"),
("Kapok", Slot(14, 17), "Lina")]
for room, slot, member in requests:
try:
service.book(room, slot, member)
print(f"OK {member:<5} {room}")
except ValueError as e:
print(f"REFUSED {member:<5} {room}: {e}")
print(notifications)
OK Awa Baobab
REFUSED Kofi Baobab: Baobab already booked from 9 to 11
OK Kofi Baobab
REFUSED Lina Kapok: outside opening hours (8 am - 8 pm)
REFUSED Lina Kapok: invalid duration: 1 to 2 h
['Awa: Baobab, 9-11', 'Kofi: Baobab, 11-13']
frozen=Truemakes slots and bookings immutable: once created, nobody can change them by mistake;overlapsholds all the conflict logic, in one line, testable on its own;- the service receives its repository and its publish function: it does not know that notifications end up in a list;
- the 11-to-13 booking is accepted: it starts when the other one ends, with no conflict.
The tests
The rules are isolated: they are tested directly, with an in-memory repository and a publish function that does nothing.
import unittest
from dataclasses import dataclass
@dataclass(frozen=True)
class Slot:
start: int
end: int
def overlaps(self, other):
return self.start < other.end and other.start < self.end
class MemoryRepository:
def __init__(self): self.bookings = []
def bookings_for(self, room): return [b for b in self.bookings if b[0] == room]
def add(self, b): self.bookings.append(b)
class BookingService:
def __init__(self, repository, publish): self.repository, self.publish = repository, publish
def book(self, room, s, member):
if s.start < 8 or s.end > 20: raise ValueError("hours")
if not 0 < s.end - s.start <= 2: raise ValueError("duration")
if any(b[1].overlaps(s) for b in self.repository.bookings_for(room)): raise ValueError("conflict")
self.repository.add((room, s, member)); self.publish("booking_created", (room, s, member))
class TestBooking(unittest.TestCase):
def setUp(self):
self.events = []
self.service = BookingService(MemoryRepository(), lambda name, b: self.events.append(name))
self.service.book("Baobab", Slot(9, 11), "Awa")
def test_touching_slots(self):
self.service.book("Baobab", Slot(11, 13), "Kofi")
def test_conflict_refused(self):
with self.assertRaises(ValueError): self.service.book("Baobab", Slot(10, 12), "Kofi")
def test_other_room_free(self):
self.service.book("Kapok", Slot(10, 12), "Kofi")
def test_max_duration(self):
with self.assertRaises(ValueError): self.service.book("Kapok", Slot(12, 15), "Lina")
def test_hours(self):
with self.assertRaises(ValueError): self.service.book("Kapok", Slot(19, 21), "Lina")
def test_notification(self):
self.assertEqual(self.events, ["booking_created"])
r = unittest.TestResult()
unittest.defaultTestLoader.loadTestsFromTestCase(TestBooking).run(r)
print(r.testsRun, "tests,", len(r.failures), "failure(s),", len(r.errors), "error(s)")
6 tests, 0 failure(s), 0 error(s)
setUp runs before each test: each one starts again from a fresh service with a single booking, without inheriting the effects of other tests. The code is compacted here to fit in the block; in a project, the tests would import the application module instead of copying it.
Mini-lab: a new rulePython 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
Your turn
Worked exercise
Worked exercise: cancellation
Add a cancel(room, slot, member) method to the service. Only the member who booked can cancel; otherwise, a PermissionError is raised. A cancellation publishes the "booking_cancelled" event. Check that after cancellation, the slot can be booked by someone else.
Hint 1
remove(booking) method.Hint 2
ValueError; if the member differs, a PermissionError.Show the solution and common mistakes
from dataclasses import dataclass
@dataclass(frozen=True)
class Slot:
start: int
end: int
def overlaps(self, other):
return self.start < other.end and other.start < self.end
@dataclass(frozen=True)
class Booking:
room: str
slot: Slot
member: str
class MemoryRepository:
def __init__(self): self.bookings = []
def bookings_for(self, room): return [b for b in self.bookings if b.room == room]
def add(self, b): self.bookings.append(b)
def remove(self, b): self.bookings.remove(b)
class BookingService:
def __init__(self, repository, publish):
self.repository, self.publish = repository, publish
def book(self, room, slot, member):
if any(b.slot.overlaps(slot) for b in self.repository.bookings_for(room)):
raise ValueError("slot already booked")
b = Booking(room, slot, member)
self.repository.add(b)
self.publish("booking_created", b)
def cancel(self, room, slot, member):
found = next((b for b in self.repository.bookings_for(room) if b.slot == slot), None)
if found is None:
raise ValueError("no booking on this slot")
if found.member != member:
raise PermissionError(f"only {found.member} can cancel this booking")
self.repository.remove(found)
self.publish("booking_cancelled", found)
log = []
service = BookingService(MemoryRepository(), lambda name, b: log.append(f"{name} ({b.member})"))
service.book("Baobab", Slot(9, 11), "Awa")
try:
service.cancel("Baobab", Slot(9, 11), "Kofi")
except PermissionError as e:
print("Refused:", e)
service.cancel("Baobab", Slot(9, 11), "Awa")
service.book("Baobab", Slot(9, 11), "Kofi")
print(log)
Refused: only Awa can cancel this booking
['booking_created (Awa)', 'booking_cancelled (Awa)', 'booking_created (Kofi)']
Since Slot is a dataclass, b.slot == slot compares values (start and end), not object identity: a slot recreated identically is indeed found.
Common mistakes:
- Checking the member after removing the booking: a refusal would come too late, the booking would already be gone.
- Publishing the event before the actual removal: if the removal fails, subscribers would have announced a cancellation that never happened.
Summary
- 1Immutable dataclasses (frozen=True) describe the domain with no risk of accidental change.
- 2The service concentrates the rules and receives its dependencies: repository and event publishing.
- 3Two intervals overlap if each starts before the other ends, with strict inequalities.
- 4Boundary tests (touching slots, maximum duration) protect the most fragile rules.
- 5setUp prepares a fresh state before each test: tests stay independent.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.