Subsection 7.2.2 Preventing Bugs
The bugs that cost the least time are the ones that never happen, and the practices below are the ones that prevent them:
-
Plan the design on paper (block diagrams, pseudocode, state diagrams) before writing code.
-
Use the file header to record what the file is, the hardware it expects, and its history.
-
Write in small chunks and test as you go.
-
Strive for readable code, with descriptive names.
-
Use functions. A good function has one clear objective: “set up the UART”, “get a value from the ADC”.
-
Comment as you go, to narrate your process and leave notes for the next person.
-
Use named constants (
constor#define) rather than literal “magic numbers”. -
Delete commented-out code from the final version.
One more habit belongs on this list, and it is about choosing a loop. Use
for when the number of iterations is known in advance, for (i = 0; i < N; i++), and while (or do ... while) when it is not. C does allow break to exit a for loop early, but if you find yourself reaching for it, a while loop is usually the better fit.
