Most programming languages have a facility for adding informal text to the source text of programs: comments. Comments have an obvious role in aiding the reader of a program (even the most mnemonic identifiers cannot tell the whole story). Effective commenting requires long practice, and a good feel for the kind of detail that the reader needs.
It is not appropriate to use a vast amount of comment text; that can be as bad as none at all. The intelligent reader needs signposts and hints - not impenetrable detail, nor a wilderness.
One important point before discussing commenting style in detail:
Comments have two important roles:
// The algorithm used is search with sentinel
// Scan salesTable looking for any zeros
// Check whether x is in range
// Processes marks and reports final grades
describes purpose, and
// Each student is represented by an object of class MarkRecord
// The results are stored in an array of ClassRecords
is a useful hint about internal workings, but not in unnecessary detail.
// Prints the contents of the database in alphabetic order
describes purpose, whereas
// Copy array telNumbers into tempNumbers.
// Bubblesort tempNumbers into alphabetic order.
// Then output the entries in tempNumbers on successive lines.
describes the mechanism.
Note: Comments should never just re-state what is evident from the program code itself. The following, for example, are pointless:
car = car+1; // Add one to cars
g.drawRect(50,50,10,20); // Call drawRect with parameters 50,50,10,20
Better would be purpose oriented comments:
car = car+1; // One more sold
g.drawRect(50,50,10,20); // Draw the chimney
// Processes marks and reports final grades
// Each student is represented by an object of class MarkRecord
// The results are stored in an array of ClassRecords
// Fred Bloggs March 1995
// John Doe June 1996: Standard deviation calculation added
For example, to illustrate these ideas:
private void find(TelNumber[] directory, int theNumber) {
// This method searches for the telephone number theNumber in
// directory.
// A message is written out indicating
// whether or not theNumber was found.
// Uses linear search with a sentinel.
...
}
It can be a useful practice to put a comment at the end of
each method body indicating which method
it is the end of. (Some programming languages enforce this!)
These comments should be brief, and certainly not on every line. The style of comments should again be to help the reader to understand the purpose of the commented statements; a comment which simply says what can be read from the program code itself is no use.