Code comments are good right? Well, not if there are too many!

Published on 2010-10-21.

Too much commenting makes the code difficult to navigate. Experienced programmers try to create code that is self-explaining. Good code is almost always self-explaining.

Bad code doesn't need comments, it needs to be refactored.

Comments in code shouldn't describe the obvious and comments shouldn't describe how the code works, it should describe the intent of the code. How the code works must be obvious from the code itself.

This is an example from a PHP application of completely useless commenting:

/**
 * Global variable
 * @global integer $GLOBALS['_myvar']
 */
$GLOBALS['_myvar'] = 6;

/**#@+
 * Constants
 */

/**
 * First constant
 */
define('testing', 6);

/**
 * Second constant
 */
define('hello', strlen('hello'));

/**
 * File being parsed, used in every add function to match up elements with
 * the file that contains them
 *
 * This variable is used during parsing to associate class elements added
 * to the data structures that contain them with the file they reside in
 * @see addClass(), addMethod(), addVar(), nextFile()
 * @var string
 */
var $curfile;

/**
 * class being parsed, used to match up methods and vars with their parent
 * class
 *
 * This variable is used during parsing to associate class elements added
 * to the data structures that contain them with the file they reside in
 * @see addMethod(), addVar()
 * @var string
 */
var $curclass;

It is almost impossible to locate the actual code in all the comment clutter. Maybe the use of a variable isn't self-explaining, but there is such a thing as "comment overkill".

A much better approach is to use long self-explanatory variable names rather than comments.

If you need good comment inspiration take a look at the C code from the OpenBSD CVS Repository or the Linux Kernel Git Repository.

/*
 * Avoid obvious comments such as
 * "Exit 0 on success."
 */
exit(0);