Design · lesson 3 of 10
Ideas in this lesson
AModulea group of code with one job
BCoupling and cohesionhow tied together, how focused
CInformation hidingParnas, 1972
DInterfacewhat a module promises the rest

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.py is about the queue rules.
  • Coupling: how much one module depends on the inside of another. Low coupling: queue.py doesn'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

  1. next_number(): the next free number today

  2. is_open(time): is the centre giving out numbers?

  3. who_is_next(): picks the next patient, with the priority lane

  4. send_text(phone, message)

  5. read_incoming(request): turns the SMS company’s request into a phone number and words

  6. save_ticket(ticket)

  7. tickets_for(day)

  8. delete_old_tickets(days=30)

  9. counter_page(): the page counter staff use

  10. screen_page(): the waiting-room display

  11. sign_in(name, password)

  12. monthly_counts(month)

  13. report_as_spreadsheet(counts)

  14. estimate_wait(number): “about 40 minutes”

  15. reply_for(result): the words of the reply text

Two weeks, with and without

  1. Monday Ate Cora asks: can priority numbers start with P, like P07, so the counter can tell them apart?
  2. Monday Marco changes how numbers are made in the queue code.
  3. Tuesday The texts still say “number 7”: the SMS code built its own message from the number.
  4. Wednesday The admin page crashes: it sorted numbers as integers, and P07 isn’t one.
  5. 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

Spot the trapMarco

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

What is information hiding, as Parnas described it?
queue.py builds the reply text and calls the SMS company’s web address directly. What’s the problem?
Why does an interface need more care than the code behind it?

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.

All sources for Simple Software Development