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!

2 comments:

CodeCracker 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