Code Documentation Standards

Documenting your code well is almost as important as making sure it is bug free. In fact, many people would argue that it is more important, because if you document it well, at least somebody else can come in and fix your bugs later on.

I like using the *doc format for code documentation (phpdoc, javadoc, etc.) because it is fairly standard and easily machine+human readable. It uses @ identifiers for various peices of documentation (e.g. @param, @return, @see, etc.)

For the code itself, I try to follow the Zend Framework standards. In brief, these are:

For a great overview of code+documentation best practices in PHP (as well as other PHP best practices), see Matthew Weier O'Phinney's Best Practices with Zend Framework slideshow.

The following is a code sample outlining good code+documentation practices. It is written in PHP, but the concepts can be applied to any similar language. Note the $Id: $ tag; I generally like to configure subversion to automatically set that tag.

<?php
 
/**
 * MyBigClass 
 * 
 * MyBigClass lets you do great things. Note we try to keep all lines, including comments, 
 * under 75-85 chars
 * 
 * @author David Ordal, david -at- ordal.com
 * @package bigclass-tool
 * @version $Id: mybigclass.php 3259 2009-03-15 22:54:21Z dordal $
 *
 */
 
// class names are declared in MixedCase, and the open bracket goes on the next line
class MyBigClass 
{
 
    // constants are declared in ALL_CAPS
    const AW_LANGUAGES = 'en';
    const AW_COUNTRIES = 'US';
 
    public $setupList = null;              // variables are declared in camelCase
    private $_apiSoapClient = null;        // and private/protected variables start with an
                                           // underscore
 
    /**
     * __construct(): constructor function. Note we document any parameters
     *
     * @param    string $email email address of the account being accessed
     * @param    string $password password of the account being accessed
     *
     */
    public function __construct($email, $password) {
        // do stuff here to construct the object. Note that 
        // curly braces for functions are on the same line
 
    }
 
    /**
     * getData(): return data from this object
     * 
     * @param    string $keyword the keyword in question
     * @return    array
     *
     */
    public function getKeywordData($keyword) {
        $myArray = array();
        // do keyword data lookup and put it into $kwArray
        return $myArray;
    }
}
 
?>