I have forgotten
my Password

Or login with:

  • Facebookhttp://facebook.com/
  • Googlehttps://www.google.com/accounts/o8/id
  • Yahoohttps://me.yahoo.com
Index » Programming » Tutorials » C & C++ » C++ Gotchas »

Gotcha #1: Avoid Excessive Commenting

CodeCogs\′s Photo
5 Nov 07, 9:16AM
Gotcha #1: Avoid Excessive Commenting
If a program is carefully structured and written then the use of many comments can be avoided. For example, function names should broadly represent the purpose of the function, similarly variable names should represent what they contain - not least in function declarations.

Consider the following comment added to this this simple C statement:
a=b;  // assigns b to a
The comment adds no further information, and in fact could potentially add confusion if the programmer actually miss-typed the comment, or perhaps more likely, failed to update the comment when changing the code. Note if this simple statement is subsequently changed, then two bits of code need to be amended (wasting time).

So if you saw:
c=b;  // assigns b to a
Then you wouldn't honestly know if the comment or the C statement was correct and would have to trace back to fix this.

A similar problem arises with class definitions (and struct's), i.e
class A
{
  // public interface
  public:
     A();   // default constructor
     ~A(); // destructor
     /* .... */ 
 
  // private interface
  private:
     /* .... */
};
None of these comments add any information and are obvious to a good programmer. As as Stephen points out: "If a maintainer has to be reminded of the meaning of a public: label, then you don't want that person maintaining your code"

Good Practice

As a simple set of general rules, consider following these:
  • give function names that represent their purpose, i.e.
void set_x(int x) { ... }
then provide a simple (perhaps one line) comment about this function and what it does, rather than how it does it.
  • use commonly know functions, i.e.
printf("\N Hello world");
does not need further comments, nor would any other standard C/C++ command.
  • Try to keep the length of functions short. A function that is 1 page long will be a twice as easy to understand than one thats expanded over onto a 2nd page.
Currently you need to be logged in to leave a message.