Separate Object Creation from Persistence
Core idea
A factory chooses or constructs a domain object. A repository exposes domain-oriented persistence operations such as add and get, hiding storage details from service code. Keep the creation and storage policies separate when they change independently. Repository interfaces should state missing-key, duplicate and transaction behavior.
from dataclasses import dataclass@dataclass(frozen=True)class Item: code: str units: intdef make_item(code, units): if not code or units < 0: raise ValueError('invalid item') return Item(code, units)print(make_item('A', 4))Creation checks the contract without saving anything; inputs are assumed str and int.
Expected output:
Item(code='A', units=4)Store through a repository
class Repository: def __init__(self): self.rows = {} def add(self, code, units): if code in self.rows: raise ValueError('duplicate') self.rows[code] = units def get(self, code): return self.rows[code]r = Repository()r.add('A', 4)print(r.get('A'))This in-memory implementation rejects duplicates and raises KeyError for missing codes. It is not durable.
Expected output:
4Common mistake
Do not promise persistence from an in-memory fake or hide transaction boundaries. A factory need not automatically save its result.
Practice
Implement the same add/get contract using a temporary SQLite database; test duplicates and missing codes on both implementations.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Factory and repository
Check your understanding of factory and repository.
What is printed?
def make(n): return {"units":n}print(make(2)["units"])What is printed?
rows={"A":4}print(rows.get("B",0))What belongs in the repository contract?
What is the responsibility of a factory?