Show contents
Chapter 2 of 7 · 20 min
Layers and dependencies
By the end of this chapter, you'll be able to
- Describe a three-layer architecture: presentation, service, data access
- Define an interface with typing.Protocol
- Inject a dependency into a service
- Replace data access with a test version
Three layers
A very common organisation separates:
- presentation: the interface with the user or other programs (web page, API, command line). It receives requests and formats responses;
- services (or business layer): the application's rules. How many books can be borrowed? What happens when one is late?
- data access: storage, in a file, a database or elsewhere.
The golden rule: dependencies point towards the centre. Presentation calls the services; services use data access through an interface; business rules know nothing about the web or SQL.
The concrete, interchangeable implementation does the actual storage work.
Text description of the animation
- Presentation receives the request and turns it into a service call.
- The service applies the rules: book available? limit reached?
- It goes through the repository interface, without knowing how books are stored.
- The concrete, interchangeable implementation does the actual storage work.
An interface with Protocol
In Python, typing.Protocol describes an interface: the methods an object must have, without saying how they are written. Any class that has these methods fits, without having to inherit from anything.
from dataclasses import dataclass
from typing import Protocol
@dataclass
class Book:
id: int
title: str
available: bool = True
class Repository(Protocol):
def find(self, book_id: int) -> Book | None: ...
def save(self, book: Book) -> None: ...
class MemoryRepository:
def __init__(self, books):
self.books = {b.id: b for b in books}
def find(self, book_id):
return self.books.get(book_id)
def save(self, book):
self.books[book.id] = book
class LoanService:
def __init__(self, repository: Repository):
self.repository = repository
def borrow(self, book_id):
book = self.repository.find(book_id)
if book is None:
raise ValueError(f"unknown book {book_id}")
if not book.available:
raise ValueError(f"“{book.title}” is already on loan")
book.available = False
self.repository.save(book)
return book
repository = MemoryRepository([Book(1, "Things Fall Apart"), Book(2, "So Long a Letter")])
service = LoanService(repository)
print(service.borrow(2))
try:
service.borrow(2)
except ValueError as e:
print("Refused:", e)
Book(id=2, title='So Long a Letter', available=False)
Refused: “So Long a Letter” is already on loan
Repositorycontains no code: only signatures (...means “no implementation here”);LoanServicereceives its repository as a parameter: this is dependency injection. It does not create its own storage;- the rules (unknown book, already on loan) are in the service, and nowhere else.
Tomorrow, a SQLRepository with the same methods can replace MemoryRepository without touching a single line of the service.
Testing thanks to injection
Because the service depends on an interface, you can give it a test repository that records what it is asked. This checks the service's behaviour, without a database:
from dataclasses import dataclass
@dataclass
class Book:
id: int
title: str
available: bool = True
class SpyRepository:
def __init__(self, books):
self.books = {b.id: b for b in books}
self.calls = []
def find(self, book_id):
self.calls.append(("find", book_id))
return self.books.get(book_id)
def save(self, book):
self.calls.append(("save", book.id))
class LoanService:
def __init__(self, repository):
self.repository = repository
def borrow(self, book_id):
book = self.repository.find(book_id)
if book is None or not book.available:
return False
book.available = False
self.repository.save(book)
return True
spy = SpyRepository([Book(1, "Ambiguous Adventure", available=False), Book(2, "Small Country")])
service = LoanService(spy)
assert service.borrow(2) is True
assert service.borrow(1) is False
assert service.borrow(9) is False
print(spy.calls)
[('find', 2), ('save', 2), ('find', 1), ('find', 9)]
The call log shows that only the book actually borrowed is saved: an unavailable or unknown book causes no write. This kind of check would be heavy with a real database to prepare and clean up.
Mini-lab: another storagePython 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: the loan limit in the right place
Add the rule “3 loans maximum per member” to the service, and only there. The repository provides loan_count(member_id). The method borrow(book_id, member_id) returns "ok" or the reason for refusal. Test it with an in-memory repository where member 7 already has 3 loans and member 8 only one.
Hint 1
Hint 2
{member_id: count}.Show the solution and common mistakes
class MemoryRepository:
def __init__(self, books, loans):
self.books = books
self.loans = loans
def find(self, book_id):
return self.books.get(book_id)
def loan_count(self, member_id):
return self.loans.get(member_id, 0)
def record_loan(self, book_id, member_id):
self.books[book_id]["available"] = False
self.loans[member_id] = self.loans.get(member_id, 0) + 1
class LoanService:
LIMIT = 3
def __init__(self, repository):
self.repository = repository
def borrow(self, book_id, member_id):
book = self.repository.find(book_id)
if book is None:
return "unknown book"
if not book["available"]:
return "book already on loan"
if self.repository.loan_count(member_id) >= self.LIMIT:
return f"limit of {self.LIMIT} loans reached"
self.repository.record_loan(book_id, member_id)
return "ok"
repository = MemoryRepository({1: {"available": True}, 2: {"available": True}}, {7: 3, 8: 1})
service = LoanService(repository)
print(service.borrow(1, 7))
print(service.borrow(1, 8))
print(service.borrow(1, 8), repository.loans)
limit of 3 loans reached
ok
book already on loan {7: 3, 8: 2}
The limit is a class constant, LIMIT: the day the library moves to 5 loans, a single line changes, and every presentation (web, mobile, desk) follows.
Common mistakes:
- Marking the book as on loan before checking the limit: a refusal would leave the book blocked, unavailable to everyone.
- Putting the check in the repository: storage does not need to know the library's rules. With another repository, the rule would disappear.
Summary
- 1A layered architecture separates presentation, services (business rules) and data access.
- 2Dependencies point towards the centre: business rules know neither the web nor the database.
- 3typing.Protocol describes an interface; any class with the right methods fits.
- 4Dependency injection (passing the repository to the service) makes changing storage and testing easy.
- 5A business rule lives in one place: copying it into every screen makes it diverge.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.