Grade 9 Computer Science · Abstraction
Common mistakes about abstraction
Six mistakes, most of them abstracting too early or hiding too much.
The code will be replaced, the name will stay
The lines inside a function you will rewrite several times, and no one will notice. Its name and what goes in and comes out you will almost never be able to change. So where is most of the thought worth spending — and why do most beginners do the reverse?
Abstraction is the most powerful tool a programmer has, and precisely for that reason it is also the tool easiest to use wrongly. All the mistakes here are correct use of the tool in the wrong place.
- All hiding is good abstraction — What affects the user must be revealed. Ask: will the user have to take this into account?
- A good abstraction does not leak — Every abstraction leaks somewhere. Ask: is this leak costing me anything now?
- Duplication is always worse than abstraction — A wrong abstraction costs more than duplication. Ask: how many cases have I actually seen?
- Abstract at once on seeing a similarity — With two it is hard to tell shared from incidental. Ask: what exactly is shared, and what only looks alike?
- A long function is the problem — Mixed levels are harder than length. Ask: do all the lines speak at the same height?
- When an abstraction leaks it must be given up — It still saves in all the other cases. Ask: how many layers must actually be understood here?
Example 1 — an answer that is too long
- Ask what must be known in order to use it.
- The answer lists five conditions.
- A sign the abstraction is not doing its work.
- It saved the user nothing.
Example 2 — a short answer
- One must know what goes in and what comes out.
- And what happens on failure.
- Three things, and no more.
- That is an abstraction doing its work.