Build with collaborators.
Make an object use a collaborator instead of inheriting every responsibility.
01 The idea
Composition models a has-a relationship: a report service has a storage collaborator. Dependency injection means the collaborator is supplied from outside rather than constructed secretly inside. This keeps business behaviour separate from infrastructure and lets tests supply a small in-memory substitute.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
class MemoryStore:
def __init__(self):
self.messages = []
def save(self, message):
self.messages.append(message)
class Reporter:
def __init__(self, store):
self.store = store
def publish(self, name):
self.store.save(f"Report: {name}")
store = MemoryStore()
Reporter(store).publish("Orbit")
print(store.messages)['Report: Orbit']
03 Under the hood
- 1
Reporter depends on the behaviour save(message), not on the details of a database driver.
- 2
MemoryStore is an explicit, inspectable collaborator. A file or database store can provide the same interface without changing how the report is produced.
- 3
This design makes tests narrow: assert that the expected report reaches the store. Do not create a large abstraction for every trivial function; introduce a boundary where there is real variation or an external dependency.
04 Your turn, builder
Inject a store into a notifier and verify that two messages arrive in the supplied store.
Reveal one possible solution +
class Store:
def __init__(self): self.items = []
def save(self, item): self.items.append(item)
class Notifier:
def __init__(self, store): self.store = store
def send(self, text): self.store.save(text)
store = Store()
notifier = Notifier(store)
notifier.send("Build")
notifier.send("Test")
print(store.items)05 Check your signal
What is injected into Reporter?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.