Grade 9 Computer Science · Abstraction
The price of a wrong abstraction
Why a wrong abstraction is worse than no abstraction at all.
When removing duplication makes code worse
It is easy to believe that two copies of the same code are always a mistake to be fixed. But there is a situation in which two ugly copies beat one tidy function — and whoever rushes to merge them may find, six months later, a function with seven parameters no one understands.
Until here abstraction has looked like something always worth doing. Here is the other side, and it is not obvious: an abstraction chosen wrongly costs more than making no abstraction at all — and is far harder to fix.
| The situation | What happens later |
|---|---|
| Duplication with no abstraction | Ugly, and clear what to change |
| A wrong abstraction | Parameters and conditions piling up |
The early sign: a parameter that changes behaviour
There is a sign that appears early and is worth recognising. When a parameter is added to a function whose whole role is to choose which of its behaviours will be carried out — a flag saying “do it another way”, say — that nearly always means there are two functions here squeezed into one. Two separate functions with different names will be shorter, clearer, and easier to change than either of them alone. The rule: a parameter should be a datum, not a choice between paths.
Example 1 — why duplication is clearer
- One sees there are two copies.
- Whoever changes knows to look for both.
- The mismatch is visible.
- In a wrong abstraction it is hidden.
Example 2 — a flag hiding two functions
- A parameter choosing a behaviour was added.
- Half the body runs in one case only.
- And another half in the other.
- These are two functions squeezed into one.