Code Readability, Part 1

5 Comments

The simplicity of PHP can sometimes be overwhelming, with so many different ways and approaches
to creating solutions for our problems we sometimes lose the ability to think past the current problem
and into the future. I sometimes feel overwhelmed thinking about the fact that what I write today could
still be running 15, 20, or even 30 years later (yes legacy code refuses to die, now and certainly later,)
so when I revisit the code I wrote a few months ago and look over it from time to time I still have to say
“What the hell was that guy thinking” not realizing that I was the author.

As such I'm planning on writing a short series on things to aide in code readability and this is the first post of the series.
Where I work we have established code style and naming convention guidelines, as many PHP Shops have, however we don't address all
issues that crop up from time to time. Today I'm going to try to address some quick ideas that most of you will already be familiar
with, things that will aide in the general readability of code for future generations.

Commenting Code:

Where should comments go and how many should there be, I constantly face this decision, ranging from simple methods to full
blow controllers, what needs to be documented and what is understandable enough to stand on it's own? Well my general rules that
I try to adhere to are as such:

  • If there is a decision to be made in the comment (switch statement or if clause) ex.
    [sourcecode lang='php']
    <?php
    //Checks the mode and directs accordingly
    switch ($_GET['mode']) {
        case 'index':
            include('modes/index.php');
            break;
        case 'login':
            include('modes/login.php');
            break;
    }
    ?>
    [/sourcecode]
  • Array parameters, we all know that putting more than a handful of optional parameters on a function can make a function barely usuable,
    however replacing optional parameters with an array can be just as horrible without an appropriate comment. Generally this belongs in the
    DocBlocks as such:
    [sourcecode lang='php']
    <?php
    /**
    * Simple Example function
    *
    * @params string $requiredParam
    * @params array $optionalParams (Valid Fields are: option1, option2, option3, option4)
    * @void
    */
    function exampleFunction($requiredParam, $optionalParams = null) { &hellip; }
    ?>
    [/sourcecode]
  • Any place where the logic could be fuzzy or problematic, this one is really up to the individual coder, however,
    if it's in question comment it!
  • Anything you see in the code that needs to be done at a later time or a bug that you don't have time to work on,
    most IDEs (Zend Studio, PDT, etc) support these tags and will list them for you in a panel or some other listing mechanism:
    [sourcecode lang='php']
    //@TODO: Future Todo
    //@BUG: Located or probable bug
    [/sourcecode]
  • That brings up to another point, Good API documentation is hard to sit down and write, we're Code Poets not Manual Writers,
    however this is much more easily accomplished by offering information in the code and letting an application (such as PHPDocumentor)
    go out and generate the API Documentation from that, DocBlocks are usually defined as:
    [sourcecode lang='php']
    <?php
    /**
    * Description
    *
    * @tags
    */
    ?>
    [/sourcecode]
    A list of valid @tags for PHPDocumentor is available at http://manual.phpdoc.org/HTMLframesConverter/default/phpDocumentor/tutorial_tags.pkg.html
    A quick example:
    [sourcecode lang='php']
    <?php
    /**
    * Example class which does nothing but highlight DocBlocks
    * $Id$ is usually filled in by SVN/CVS
    *
    * @author Shawn Stratton <shawn.stratton *at* gmail.com>
    * @copyright 2009
    * @package Example
    * @since $Id$
    */
    classExampleClass {

        /**
        * Contains the SomeClass passed by constructor.
        *
        * @var SomeClass
        * @access private
        */
        private $class;

        /**
        * Creates a new instance of ExampleClass
        *
        * @param SomeClass $class
        */
        function__construct(SomeClass$class) {}
        /**
        * Takes two parameters and returns True however has been replaced by
        * method x
        *
        * @param string $string
        * @param int $int
        * @return bool
        * @deprecated
        */
        functionReturnsTrue($string,$int)
        {
            return true;
        }
    }
    ?>
    [/sourcecode]

I hope this introduction will help some of you out there, I must admit I'm not much of a writer. I hope to publish
part 2 by the end of this week (January 12 th, 2009) which will deal more on how to format conditions and error checking
to where it's not difficult to decypher.

MXWest

Excellent topic I will definitely be back for part 2. All too often I run into code that is nearly impossible to decipher without reformatting it. Legible code is so key to advancing many of the terrific open source applications and services that it really should be discussed more often.

2009-01-13 12:30:17

David Ferguson

While writing comments in the code is an excellent thing to do. I feel I have the hardest time motivating myself to do it while I'm writing the code, because I'm more interested in getting the job done. At that point I'm not worried about figuring it out later. Then once you get done with the code, its just a pain to go back and step through all the code and do it. I have been trying to make a conscious effort to include more documentation in my code lately. This is just a bad habit of mine, and I'm sure many others as well.

2009-01-13 13:09:34

Shawn Stratton’s Blog: Code Readability, Part 1 | How2Pc

...awn Stratton’s Blog: Code Readability, Part 1 January 14th, 2009 01:40 Shawn Stratton has posted the first part of his series looking at “Code Readability”. This part focuses on something that is oft...

2009-01-13 18:46:30

Brenelz

It is indeed necessary to comment and make your code readable as more than likely another coder will access your work at sometime or another.

-Brenelz

2009-01-14 16:43:58

Chuck Burgess

My key guideline on commenting is making sure I spell out the "why" behind the code logic, much more so than the "how" of the logic. Most anti-commenters will argue "don't repeat in comments what I can clearly read in the code itself". While this argument holds some weight with me, I can say that as someone who's spent a majority of his time reading other people's code and having to divine what's going on, it's the "why" behind the logic that I spend the most time researching, greater by far than researching the "how".

If I can understand the "why", then the "how" almost always makes more sense, because I then have some "context" around the "how". Without knowing the "why", I'm left constructing assumptions about the "how". Many times this makes it more difficult to maintain the code, as I can't be 100% sure about what I *think* is a bug or about where a proper place for a change should go.

2009-01-19 09:58:42