CSCI 1321 (Principles of Algorithm Design II), Fall 2001:
Tips for Writing Clear and Well-Documented Code
Something that early programmers did not fully appreciate
is that programs tend to take on a life of their own,
being reused and modified over a period of years, often
by people other than their original authors.
The better a job the original author did of documenting the
program and writing it clearly, the easier it will be to reuse
and modify.
By ``documentation'' I mean comments at the start of the program
that help potential users understand exactly
what the program does without necessarily understanding
how and definitely without reading the whole program.
Generally speaking, these comments should describe the program's
inputs (command-line arguments, file input, input from standard input)
and outputs (file output, output to standard output) and
how they are related.
The object of these suggestions is to make the code clear and
readable for the human reader, perhaps a programmer who wants to
reuse it with modifications.
Here are some tips for writing clear code.
- If a variable's purpose is not obvious from its name,
add to its a declaration a short comment describing its
intended meaning and usage.
This can also be a help in thinking about how to write
the program in the first place.
Note that C++ allows you to put the comment on the same
line with the declaration.
- Choose a consistent indentation style for loops and
conditional constructs (if / else).
That is, indent the statements that make up the body
of a loop, and indent the statements to be executed
as part of an if or an else.
This makes the control flow of the program stand out
better.
- If there is something tricky about the program -- something
you think will confuse the reader -- include
a comment or a block of comments to explain what's
going on.
- If the program is long, use comments to mark it off into
sections and indicate the overall purpose of each section.
- But don't include comments just to have comments!
For example, the comment
//declare the variables
is useful only in example programs for beginners;
after your first few programs you shouldn't need such a comment.
Also, comments that just echo what the code is doing --
for example,
count++; // increment count
-- are not helpful (again except in example programs for
beginners).
- If your program contains more than one function, include for
each function comments that describe its purpose, parameters,
and return value. You may put these comments before the
function's prototype or before its definition.
Berna Massingill
2001-10-03