6.1.1 – Decompose and abstract a problem
Turn a requirement into relevant data, clear subproblems and a workable plan. Connect the jobs through explicit inputs and results, then check that the solution covers the requirement.
Choose the information the program needs
Decomposition breaks a programming problem into purposeful subproblems that can be solved and combined. Abstraction keeps the information needed for the required result and leaves out irrelevant detail. These decisions depend on the actual requirement.
A quiz organiser records scores, player names, favourite colours and recording times. The required program must display the mean of a nonempty list of whole-number scores and how many scores are at least a supplied target.
The score values are needed for both results, and the target decides which values count. Names, colours and times cannot change either required output, so they do not need to enter this calculation. If the requirement changes to name everyone who reached the target, names become relevant. Abstraction is not simply deleting as much data as possible.
State assumptions before designing: the score list is nonempty, scores and target are valid integers, and equality counts. There is no requirement to validate keyboard input or sort the scores. Adding those jobs would not solve a missing requirement.
Define jobs and the data between them
For the quiz requirement, a useful plan is:
- obtain the score list and target;
- total every score and count those meeting the target;
- divide the completed total by the number of scores;
- display the mean and count.
A subproblem should have a clear result. “Do the maths” is too vague; “total every score once” can be implemented and checked. Jobs need not be equal in size, and each need not become a separate function. One processing function can total and count in the same loop.
| Job | Inputs | Result needed by the next job |
|---|---|---|
| Analyse scores | nonempty score list, target | mean and target count |
| Display summary | mean, target count | two labelled output lines |
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account