Grade 12 Computer Science · Reading and tracing code
Reading code that is not yours
Why starting from the first line is the worst way.
Half an answer from a line you have not finished reading
You open three hundred lines someone else wrote, and you need to know just one thing from them. Starting at the first line and working down is the slowest way. Half the answer is in a single line, before the body is even read. Which line, and what else must come before the reading?
Most of the time spent with code is not in writing it — it is in reading existing code, usually someone else’s, and often your own from half a year ago. That skill is nearly always learned the hard way, and it has a method.
// step 1 — the signature alone:
static int[] mystery(int[] a, int k)
// takes an array and a number, returns an array.
// returns a NEW array, or the same one? the name does not say.
// step 2 — the structure:
// one loop over a, one condition inside, one return at the end.
// step 3 — only now, the lines.Asking a question before reading
Reading with no question is endless reading — there is always another line. It is worth stating to yourself what exactly you want to know before starting: what does the operation return on an empty input? Where does this field change? Why is the result smaller by one? The question settles which lines are relevant, and most lines are not. Without a question you will read everything and understand less.
| The stage | What one checks |
|---|---|
| The signature | What goes in, what comes out, what the name promises |
| The structure | Loops, conditions, return points |
| The lines | Only those relevant to the question |
Example 1 — why the signature gives half
- It says what goes in and what comes out.
- And the name says what is promised.
- Without reading a single line.
Example 2 — why reading without a question does not end
- There is always another line.
- And there is no criterion to stop.
- The question settles what is relevant.