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 of completely useless commenting:

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

/**#@+
 * Constants
 */

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

/**
 * Second constant
 */
define('anotherconstant', 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 commenting because every single variable contains a large amount of comments. 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 self-explanatory variable names. It is much better to use a long self-explanatory variable name than it is to compensate a bad variable name by comments.

If you need good comment inspiration take a look at the C code from the OpenBSD GitHub repository mirror. It is code quality at it's highest!