#009 – How to use comments

I’m a big advocate of comments. It conveys the programmer’s intent, which is very useful if you’re interpreting someone else’s code.

How to use comments

A comment should communicate what a function or library does. For example:


// This program calculates the student's final grade based on their test and homework scores.
// This function uses Newton's method to approximate the root of a given equation.

A programmer should read the comment and get an idea of what the program does without interpreting a single line of code.

A comment shouldn’t simply convey what a statement is doing. E.g.

// Set sight range to 0
sight = 0;

The comment doesn’t provide any new information.

Good comments explain why something is occurring

// We need to multiply quantity by 2 here because they are bought in pairs
cost = quantity * 2 * storePrice;

Comments can be used to justify why a programmer choose one implementation over another:

// We decided to use a linked list instead of an array because
// arrays do insertion too slowly.

Commenting out code

In addition to providing documentation, comments can be used for the following:

  1. Assist in debugging. If a program fails to compile, you can comment out code sequentially to identify the culprit.
  2. Permit compilation. If a block of new code is causing a compilation error, you can comment it out and return to it later.
  3. Refactoring code. Rather than delete the old code, program the new code and test it, you can comment out the old code as a backup. Then, when the new code passes the tests, you can remove the old code.

Leave a Reply

Your email address will not be published. Required fields are marked *