Grade 7 Computer Science · What a program is

Breaking a problem into steps

A problem too large to solve is a problem not yet broken down enough.

Four stages hiding in one task

“Work out an average” sounds like a single task. In fact four separate parts are hiding in it, and only one of them can fail. Which one — and how can you know before writing a line of code?

The first difficulty in programming is not the code — it is knowing where to start. The tool for that is one: decompose. The question is not “how do I write this” but “what is the first stage, and what exactly does it take in and give back”.

The checkThe question one asks
Stands on its ownCan it be explained without the rest?
A clear interfaceWhat goes in and what comes out?
Testable separatelyCan it be run on a small example?

A full example: computing an average score

The problem “compute an average” sounds small, and still it has four separate stages: take in the scores, add them, count how many there are, and divide. Each stands on its own, for each it is clear what goes in and what comes out, and each can be tested separately. Note that the fourth stage is the only one that can fail — division by zero when there are no scores — and that is exactly the edge case from the previous lesson.

scores = [90, 80, 70]
total = 0
for s in scores:
    total = total + s
count = len(scores)
print(total / count)

Example 1 — checking whether a part stands on its own

  1. Try to explain what the part does.
  2. If the explanation needs another part — it is dependent.
  3. Then the boundary runs in the wrong place.
  4. Move the boundary and try again.

Example 2 — why a clear interface saves time

  1. It is known that the adding stage takes a list and returns a number.
  2. It can be checked on three numbers.
  3. If the result is right, one can forget about it.
  4. The remaining problem is one stage smaller.
Four stages, and each can be tested before moving on to the next.