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 level | What it deals with |
|---|---|
| High | What the system does |
| Middle | How each stage is carried out |
| Low | Computations 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
- Read the names of the lines in sequence.
- Three of them describe large stages.
- One describes a computation on characters.
- It is the one that should move into a function.
Example 2 — why it is easier to read
- Every line speaks at the same height.
- The reader builds one picture.
- There is no jump forcing a change of context.
- And it can be understood at a glance.