Modules and interfaces
Last updated
Inside the program, Pila's code still needs a shape: which functions live together, and what each group lets the others see. Get it right and a change stays in one place; get it wrong and one small change breaks three things nobody expected. In this lesson you'll meet coupling and cohesion, Parnas's rule about hiding decisions, and split Pila's functions into modules with clear boundaries.
By the end of this lesson you can
- Explain coupling and cohesion, and why low coupling and high cohesion help
- Apply information hiding: put each decision likely to change behind an interface
- Split a system's functions into modules with clear boundaries
Coupling and cohesion
A module is a group of code with one job: in Python, usually one file. Two words describe how well a system is split into modules:
- Cohesion: how closely the things inside a module belong together. High cohesion: everything in
queue.pyis about the queue rules. - Coupling: how much one module depends on the inside of another. Low coupling:
queue.pydoesn't know or care how texts are sent.
Aim for high cohesion and low coupling. Then a change to one job means a change to one module, and the others don't notice. Separation of concerns is the same idea said another way: each part of the code deals with one concern.
Hide what might change
In 1972 David Parnas compared two ways of splitting the same program into modules. The usual way followed the steps of the processing: first this, then that. His way gave each module one design decision likely to change, and hid it from the rest. When decisions changed, his version needed far fewer modules changed. This is information hiding.
For Pila, the decisions likely to change include: which SMS company sends texts, how the queue is stored, the health office's report format, and the opening hours. Compare two versions of the code that takes a number:
# Without hiding: the SMS company's details are in the queue code
def take_number(request):
phone = request.form["msisdn"] # the company's field name
number = next_number()
requests.post("https://api.example-sms.ph/v2/send",
json={"to": phone, "body": f"You are number {number}"})# With hiding: only sms.py knows about the company
def take_number(phone):
number = next_number()
sms.send_text(phone, f"You are number {number}")In the first, a new SMS company means hunting through every file that sends a text. In the second, it means changing sms.py alone.
An interface is a promise
A module's interface is what it lets others use: its public functions, what they take, what they give back, and what they promise. Everything else is private. In Python, a leading underscore, _connect(), marks a function as internal by convention.
def send_text(phone: str, message: str) -> bool:
"""Send one text message to a Philippine mobile number.
Returns True if the SMS company accepted it. Never raises:
on failure it logs the problem and returns False.
"""That docstring is a promise. Callers rely on it; the inside can change freely as long as the promise holds. Change the promise (raise an exception instead of returning False) and every caller may break. That's why interfaces deserve more care than the code behind them.
Split Pila into modules
Here are fifteen of Pila's functions. Put each in the module where it belongs. Ask of each: which decision does it depend on, and which module hides that decision?
0 of 15 placed right
next_number(): the next free number todayis_open(time): is the centre giving out numbers?who_is_next(): picks the next patient, with the priority lanesend_text(phone, message)read_incoming(request): turns the SMS company’s request into a phone number and wordssave_ticket(ticket)tickets_for(day)delete_old_tickets(days=30)counter_page(): the page counter staff usescreen_page(): the waiting-room displaysign_in(name, password)monthly_counts(month)report_as_spreadsheet(counts)estimate_wait(number): “about 40 minutes”reply_for(result): the words of the reply text
Two weeks, with and without
- Monday Ate Cora asks: can priority numbers start with P, like P07, so the counter can tell them apart?
- Monday Marco changes how numbers are made in the queue code.
- Tuesday The texts still say “number 7”: the SMS code built its own message from the number.
- Wednesday The admin page crashes: it sorted numbers as integers, and P07 isn’t one.
- Friday The monthly report counts P07 as a new kind of patient. Nobody notices for a month.
Without modules with clear interfaces: Queue numbers were read and built in four places. Changing their format touched every one, and two were missed.
Switch to the other side to compare.
Spot the trap: utils.py
Marco has a few functions that don’t obviously belong anywhere: formatting a phone number, the opening hours, building a reply text, a date helper. He makes utils.py and puts them all there.
What happens if…
Check what you learned
Sources
Every claim on this page comes from these sources: the standard, the founding text of a method, a study, or the official record of a project, from the body that publishes it. Industry reports are labelled as such.
- David Parnas, “On the Criteria to Be Used in Decomposing Systems into Modules”, Communications of the ACM (1972): information hiding: each module hides a design decision likely to change
- IEEE Computer Society: SWEBOK Guide, version 4.0 (2024): coupling, cohesion, modularity and separation of concerns in software design