Skip to content
KALANBLON
Show contents

Chapter 1 of 7 · 20 min

Design principles

By the end of this chapter, you'll be able to

  • Recognise a function that does too much and split it
  • Explain cohesion and coupling
  • Apply the single responsibility principle
  • Reduce coupling by passing dependencies as parameters

The symptom: the function that does everything

Here is a typical function from early programs. It reads orders, computes totals with a discount, formats a report and prints it:

def process_orders(lines):
    grand_total = 0
    for line in lines:
        customer, product, quantity, price = line.split(";")
        total = int(quantity) * int(price)
        if total > 50000:
            total = total * 0.9
        grand_total += total
        print(f"{customer:<8} {product:<12} {total:>9.0f} FCFA")
    print(f"{'TOTAL':<21} {grand_total:>9.0f} FCFA")

process_orders(["Awa;wraps;4;8000", "Kofi;bag;5;12000", "Lina;bracelet;3;2500"])
Awa      wraps            32000 FCFA
Kofi     bag              54000 FCFA
Lina     bracelet          7500 FCFA
TOTAL                     93500 FCFA

It works. But how do you test the discount rule without printing anything? How do you produce the same report in HTML, or read orders from a database? Everything is tangled: reading, business rules and presentation share the same lines.

Cohesion and coupling

Two notions guide the split:

  • cohesion: how much the elements of a module serve one same purpose. We want it high;
  • coupling: how much a module depends on another's details. We want it low.

The single responsibility principle sums them up: a function, a class or a module should have only one reason to change. The function above has at least three: the line format, the discount policy, the report layout.

Split by responsibilities

from dataclasses import dataclass

@dataclass
class Order:
    customer: str
    product: str
    quantity: int
    price: int

def read_order(line):
    customer, product, quantity, price = line.split(";")
    return Order(customer, product, int(quantity), int(price))

def amount(order, threshold=50000, rate=0.10):
    gross = order.quantity * order.price
    return round(gross * (1 - rate)) if gross > threshold else gross

def text_report(orders):
    lines = [f"{o.customer:<8} {o.product:<12} {amount(o):>9} FCFA" for o in orders]
    lines.append(f"{'TOTAL':<21} {sum(amount(o) for o in orders):>9} FCFA")
    return "\n".join(lines)

orders = [read_order(l) for l in ["Awa;wraps;4;8000", "Kofi;bag;5;12000", "Lina;bracelet;3;2500"]]
print(text_report(orders))
print(amount(Order("Test", "x", 1, 60000)))
Awa      wraps            32000 FCFA
Kofi     bag              54000 FCFA
Lina     bracelet          7500 FCFA
TOTAL                     93500 FCFA
54000
  • read_order only knows the data's format;
  • amount only knows the business rule: it can be tested in one line, as here with a 60,000 FCFA order;
  • text_report only handles presentation and returns text instead of printing it: the caller decides what to do with it (print it, save it, email it).

A dataclass automatically generates a data class's constructor and display: Order gives a clear name to what was just a list of strings. Along the way, the amount is rounded with round: we avoid leaving decimals in CFA franc amounts.

The layout can change (text, HTML, PDF) without touching the calculations.

Step 5 of 5
Text description of the animation
  1. The data arrives as text.
  2. Only this function knows the format: if it changes, it is the only one to edit.
  3. The rest of the program handles a clear object, without knowing where it came from.
  4. The discount rule lives in a single place, and is tested on its own.
  5. The layout can change (text, HTML, PDF) without touching the calculations.

Pass dependencies as parameters

Coupling often hides in what a function fetches by itself: the system time, a global variable, a file, a database. By passing these as parameters, you make it predictable and testable:

from datetime import date

def is_late(due_date, today=None):
    today = today or date.today()
    return today > due_date

print(is_late(date(2026, 3, 1), today=date(2026, 3, 2)))
print(is_late(date(2026, 3, 1), today=date(2026, 2, 28)))
True
False

Without the today parameter, the result would depend on the day the test runs: a test that is green today could turn red tomorrow. This principle, injecting your dependencies instead of creating them yourself, is at the heart of the architectures in the next chapter.

Mini-lab: change the rule without breaking the restPython 3.13

Output

Click “Run”: Python will load in your browser (about 10 MB the first time).

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: separate computation from display

The following function computes an average mark and prints a grade. Split it into two functions: average(marks), which returns a number rounded to 2 decimal places, and grade(avg), which returns the text. Test them without printing anything other than the results.

def report_card(marks):
    total = 0
    for m in marks:
        total += m
    avg = total / len(marks)
    if avg >= 16: print("Very good", avg)
    elif avg >= 12: print("Good", avg)
    else: print("Pass", avg)
Hint 1
A function that returns a value is more reusable than a function that prints it.
Hint 2
grade must not recompute the average: it receives it as a parameter.
Show the solution and common mistakes
def average(marks):
    return round(sum(marks) / len(marks), 2)

def grade(avg):
    if avg >= 16:
        return "Very good"
    if avg >= 12:
        return "Good"
    return "Pass"

for marks in ([17, 15, 18], [12, 11, 14], [9, 10, 8]):
    a = average(marks)
    print(a, grade(a))
print(grade(16), grade(15.99))
16.67 Very good
12.33 Good
9.0 Pass
Very good Good

We can now test grade's boundaries directly (16 and 15.99), without crafting lists of marks that land exactly on them. And the same average can feed a chart, an export or an API.

Common mistakes:

  • Keeping the print in grade: the grade can no longer be used anywhere but the console.
  • Having grade compute the average: the two responsibilities stay coupled, and the average would be computed twice.

Summary

  1. 1A function that mixes reading, business rules and display is hard to test and to evolve.
  2. 2We aim for high cohesion (one module, one purpose) and low coupling (few dependencies on others' details).
  3. 3Single responsibility: a piece of code should have only one reason to change.
  4. 4Returning values rather than printing them lets the caller decide on presentation.
  5. 5Passing dependencies (date, data, services) as parameters makes code predictable and testable.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.