Separate Business Rules from Input and Output
Core idea
Keep calculations independent of reading files, printing and external services. An application boundary converts incoming data, calls a rule and presents its result. A pure calculation has no external side effects and depends only on its arguments, making its behavior easier to test. Separation concerns responsibilities, not a mandatory number of files.
def charge(units, price): if units < 0 or price < 0: raise ValueError('negative input') return units * priceprint(charge(3, 7))The rule needs only nonnegative integer inputs, not a terminal or database.
Expected output:
21Adapt text at the edge
def charge(units, price): return units * pricedef display(raw): units = int(raw) return f'Total: {charge(units, 7)}'print(display('3'))The adapter converts and formats; the arithmetic is independent. This example assumes valid nonnegative text.
Expected output:
Total: 21Common mistake
Do not put input() or print() in a reusable calculation merely for convenience. Keep conversion errors at the boundary; do not silently change a business rule.
Practice
Extract a delivery-cost rule from a console program; test zero, positive and invalid quantities without capturing stdout.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Separation of concerns
Check your understanding of separation of concerns.
What is printed?
def rule(n): return n*4print(rule(0))What is printed?
def fmt(n): return f"N={n}"print(fmt(2))Which layer should parse input text?
What is a benefit of a pure rule?