Compose Domain Logic and Boundary Adapters
Core idea
Keep three responsibilities separate: decode and validate bytes into records (boundary.py), calculate totals for already validated records (domain.py), and adapt standard input/output and exit status (cli.py). The app entry point calls the CLI. The domain function does not read files, print or know about JSON. The CLI reads no more than the byte limit plus one, delegates parsing and writes only after the complete report is ready. Pass data or streams explicitly to test each responsibility without a real terminal.
def summarize(rows): totals = {} for row in rows: key = row['category'] totals[key] = totals.get(key, 0) + row['amount_cents'] return totalsrows = [{'category': 'books', 'amount_cents': 125}, {'category': 'books', 'amount_cents': 275}]print(summarize(rows))print(summarize([]))The function operates on validated data and returns a value. The complete domain also returns count and total_cents.
Expected output:
{'books': 400}{}Serialize at the output boundary
import jsonfrom io import StringIOdef write_report(report, destination): destination.write(json.dumps(report, sort_keys=True) + '\n')output = StringIO()write_report({'tools': 200, 'books': 400}, output)print(output.getvalue(), end='')The adapter handles text format and newline; the domain can stay independent of stream and format choices.
Expected output:
{"books": 400, "tools": 200}Common mistake
Do not make the domain read stdin or catch every exception. A programmer bug should remain distinguishable from expected invalid input. The sample aggregator assumes validated records; it is not a public validation API.
Practice
Open the full fixture. Draw arrows from main.py to cli.py to boundary.py and domain.py. Add a test that calls summarize directly and verifies the input is unchanged.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Modular implementation
Check your understanding of modular implementation.
What is printed?
d={}for n in (2,3): d['books']=d.get('books',0)+nprint(d['books'])What is printed?
import jsonprint(json.dumps({'z':1,'a':2},sort_keys=True))Which layer knows the output format?
Why inject a destination stream?