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 check | The question one asks |
|---|---|
| Stands on its own | Can it be explained without the rest? |
| A clear interface | What goes in and what comes out? |
| Testable separately | Can 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
- Try to explain what the part does.
- If the explanation needs another part — it is dependent.
- Then the boundary runs in the wrong place.
- Move the boundary and try again.
Example 2 — why a clear interface saves time
- It is known that the adding stage takes a list and returns a number.
- It can be checked on three numbers.
- If the result is right, one can forget about it.
- The remaining problem is one stage smaller.