The elements of programming style: Documentation
Chapter 8: Documentation
The best documentation for a computer program is a clean structure. It also helps if the code is well formatted, with good mnemonic identifiers and labels (if any are needed), and a smattering of enlightening comments. Flowcharts and program descriptions are of secondary importance; the only reliable documentation of a computer program is the code itself. The reason is simple – whenever there are multiple representations of a program, the chance for discrepancy exists. If the code is in error, artistic flowcharts and detailed comments are to no avail. Only by reading the code can the programmer know for sure what the program does.
This is not to say that programmers should never write documentation. Quite the contrary. In a project of any size it is vital to maintain readable descriptions of what each program is supposed to do, how it is used, how it interacts with other parts of the system, and on what principles it is based. These form useful guides to the code. What is not useful is a narrative description of what a given routine actually does on a line-by-line basis. Anything that contributes no new information, but merely echoes the code, is superfluous.
- Make sure comments and code agree
- Don’t just echo the code with comments – make every comment count
- Don’t comment bad code – rewrite it.
- Use variable names that mean something
- Use statement labels that mean something
- Format a program to help the reader understand it
- Indent to show the logical structure of a program
- Document your data layouts
- Don’t over-comment
(1) If a program is incorrect, it matters little what the documentation says.
(2) If documentation does not agree with the code, it is not worth much.
(3) Consequently, code must largely document itself. If it cannot, rewrite the code rather than increase the supplementary documentation. Good code needs fewer comments than bad code does.
(4) Comments should provide additional information that is not readily obtainable from the code itself. They should never parrot the code.
(5) Mnemonic variable names and labels, and a layout that emphasizes logical structure, help make a program self-documenting.