Grade 9 Computer Science · Abstraction

Levels of abstraction

Why mixing levels is the commonest mistake in designing code.

A short function that is hard to read

A function has only a few lines, each of them correct, and still you have to stop and decode what it does. The problem is not the length and not the names. There is a check that takes ten seconds and needs nothing to be run, and it reveals exactly which line breaks the reading.

Abstractions are built one on another: a high-level function calls lower-level functions, and so on. The rule holding this structure together is simple to state and hard to keep, and it is probably the most useful rule for code quality.

# Mixed levels — hard to read:
orders = load_orders(path)
total = 0
for o in orders:
    cents = int(o["price"].replace(".", ""))
    total = total + cents

# One level — each line speaks at the same height:
orders = load_orders(path)
total = sum_prices(orders)
The levelWhat it deals with
HighWhat the system does
MiddleHow each stage is carried out
LowComputations on single values

The test: reading the function aloud

There is a quick and exact check. Read the names of the lines in the function in sequence, as though they were sentences. If a coherent story comes out — “load orders, compute a total, print a report” — the level is uniform. If something comes out like “load orders, replace a dot with nothing, convert to a number, print a report”, the jump is heard at once. This check works because it tests exactly what happens to the reader: they are trying to build a picture, and a jump in level breaks it.

Example 1 — recognising a jump in level

  1. Read the names of the lines in sequence.
  2. Three of them describe large stages.
  3. One describes a computation on characters.
  4. It is the one that should move into a function.

Example 2 — why it is easier to read

  1. Every line speaks at the same height.
  2. The reader builds one picture.
  3. There is no jump forcing a change of context.
  4. And it can be understood at a glance.
Read lines 8–10 aloud: each speaks at the same height. The work on the characters did not vanish — it just moved to a place of its own.