Tuesday, October 2, 2007

Tip: commenting variables/constants

For too many times, I see code like this:

// we allow only 100 words
int allow_word_count = 100;

// we allow only up to 10 users
const int MAX_USER_COUNT = 10;



What's wrong with the above?

A program should stay flexible in the face of change. How would you like to see:


// we allow only 100 words
int allow_word_count = 245;

Not very pleasant - but it happens. So, make your comments descriptive, while avoiding to use the actual value in the comment:

// we allow only this many words
int allow_word_count = 100;

// we allow only up to this many users
const int MAX_USER_COUNT = 10;


Much better!

3 comments:

sanjaymishra said...

Shouldn't the comment be as follows

// Max word permitted


// Max user supported by the system

John Torjo said...

Yup, that works too. Thanks for pointing it out :)

Best,
John

phresnel said...

It is fun to read the blog of the proclaimed "Best". Don't write comments that tell the same as the code already does. Comments should explain the "why", the "what/how" is explained in the code already ... Most of the time, no comments are needed at all. In your examples, you should better explain _why_ you artificially limit the number of users, because apart from datatype and storage limits, there is really no obvious justification to limit the number of users.