Composition and Interchangeable Components
Structural Protocols in Python
BOTIE
PEP 544 introduced Protocol for Python 3.8 to describe structural interfaces. An object can satisfy a protocol through its supported members without explicitly inheriting from that protocol. This documents interchangeable roles while leaving runtime validation and the real behavior of a component to the application.
Sources for this history
Why Must a New Sensor Rewrite the Alert Program?
Botie can read greenhouse temperatures from a live sensor or a recorded test report. The alert rule is the same, but the current function creates its own sensor internally. Testing it requires the real device, and replacing the device changes code that only needed to compare temperatures.
We can give the calculation a component that supplies readings. The caller chooses that component, while the calculation uses its stated capability. Another component can handle the result. This arrangement is composition: objects collaborate rather than placing every responsibility in one inheritance tree.
The correction is supplied for these invented thermometers; the workshop does not estimate a real calibration. It illustrates composing calculations. The Python examples introduce replaceable source and sink objects.
Step 1 of 1
Keep the calculation between replaceable boundaries
Changing a source or destination does not have to change the alert rule.
| Role | Required operation | Possible implementation |
|---|---|---|
| reading source | read returns Celsius readings | recorded batch or device adapter |
| calculation | select readings at least the limit | ordinary pure function |
| alert sink | send receives one accepted reading | memory list or explicit external sender |
reading source
- Required operation
- read returns Celsius readings
- Possible implementation
- recorded batch or device adapter
calculation
- Required operation
- select readings at least the limit
- Possible implementation
- ordinary pure function
alert sink
- Required operation
- send receives one accepted reading
- Possible implementation
- memory list or explicit external sender
Ask for a capability
The correction and alert count do different jobs. Connecting them lets a different thermometer supply the Celsius values the counter already expects.
Connect a New Thermometer to the Alert Counter
The existing alert counter expects Celsius readings. A replacement thermometer needs a correction before its readings reach that counter. The supplied multiplier and offset describe that correction; the alert rule itself still uses the same Celsius limit.
BOTIE
Alert count after correcting the readings
1
Follow the operations
1. Incoming thermometer readings
- 010
- 114
- 218
2. Calibration multiplier
1
3. Multiply
- 010
- 114
- 218
4. Calibration offset in Celsius
0
5. Add
- 010
- 114
- 218
6. Alert limit in corrected Celsius
15
7. Keep readings at or above the limit
- 018
8. Count items
1
9. Result
1
The correction is supplied for these invented thermometers; the workshop does not estimate a real calibration. It illustrates composing calculations. The Python examples introduce replaceable source and sink objects.
1. Ask for a capability
A function that needs readings can ask an object for a read method. It does not need to know how that object stores the data or talks to a device.
Passing the object as an argument makes the dependency visible. This is often called dependency injection. It can be an ordinary argument; it does not require a framework or a container.
Keep the required interface small enough that a caller can understand and implement it.
Use a component supplied by the caller
The calculation does not create or choose its own source.
class RecordedSensor:
def read(self):
return [18.0, 27.0, 23.0]
def highest_reading(source):
return max(source.read())
print(highest_reading(RecordedSensor()))27.0The source owns how readings are obtained. The function owns its calculation.
2. Describe the role with a protocol
Duck typing means using an object according to the operations it supports. A Protocol gives a static checker a named description of those required operations.
A method inside a protocol states the expected signature. The ellipsis below is a placeholder for an interface, not the implementation that obtains readings. The concrete class supplies that behavior without inheriting from ReadingSource.
Protocol annotations do not validate readings or prove that a device reports truthful measurements.
Declare the source interface
A recorded source supplies the protocol’s method through its structure.
from typing import Protocol
class ReadingSource(Protocol):
def read(self) -> list[float]: ...
class RecordedSensor:
def read(self) -> list[float]:
return [10.0, 30.0]
def read_span(source: ReadingSource) -> float:
values = source.read()
return max(values) - min(values)
print(read_span(RecordedSensor()))20.0The source is read once, and the calculation works with the returned batch.
Check yourself
Questions on Parts 1 to 2
Question 1 of 2
Which dependency does it need to know?
Question data
A calculation needs an object with read() returning Celsius readings.3. Adapt an existing interface at one boundary
A legacy object may already expose a useful operation under another name or representation. An adapter translates that interface into the role the caller needs.
Keep the translation explicit. If the device returns Fahrenheit, the adapter must establish that convention and perform a documented conversion before promising Celsius. Renaming a method does not convert its values.
An adapter belongs where one agreement becomes another.
Adapt a method name without changing the calculation
This legacy source already returns Celsius, so only the method interface needs translation.
class LegacySensor:
def fetch_celsius(self):
return [11.0, 16.0]
class SensorAdapter:
def __init__(self, sensor):
self.sensor = sensor
def read(self):
return list(self.sensor.fetch_celsius())
source = SensorAdapter(LegacySensor())
print(source.read())[11.0, 16.0]The adapter owns the method translation and returns a fresh outer list.
4. Keep effects behind an explicit dependency
A sink receives an output, such as an alert value. Passing it explicitly lets a test record calls in memory while a real application chooses its permitted destination.
Validate an entire batch before sending when invalid later input must prevent partial publication. A failure during an actual send is a different problem: earlier sends may already have occurred. The interface needs an explicit retry or reconciliation policy rather than pretending the whole operation was atomic.
The exercise sends only to local test objects. It does not establish the behavior of a real external integration.
5. Choose composition for independent responsibilities
A reading source, calibration policy and alert sender can change independently. Combining them through small interfaces avoids creating a subclass for every possible combination.
Inheritance remains useful when a genuine subtype preserves the parent interface and behavior expected by its callers. Use that relationship deliberately. Sharing a few implementation lines is not enough reason to make unrelated components inherit from each other.
The workshop corrects incoming readings before sending them into the alert-count calculation built earlier.
Check yourself
Questions on Parts 1 to 5
Question 1 of 4
What must the adapter establish?
Question data
A legacy device returns Fahrenheit. An adapter promises Celsius.Try it with Botie
Build with Botie
Write and run Python