5 Reasons Coding Standards Are Essential

5 Reasons Coding Standards Are Essential

Whenever you’re working on a project, are you consistent? Are you consistent in your coding style, consistent in your documenting, consistent in your database naming conventions? Better yet, do you and your team have a coding standard which you consistently adhere to?

If you don’t, you’re buying yourself and others a world of pain – which is painlessly simple to avoid.

Today I’m banging the drum, shouting from the street corner, calling from the cathedral spire, imploring you to do one thing, above all else – pick a coding standard and then BE CONSISTENT!

I don’t care if you hate standards, I don’t care if you think all of them are flawed, I don’t care if you feel locked in, chained up, with all your creativity is stifled.

Because if you think this way – You’re Wrong.

Poor, Inconsistent Code – Causes You Pain

I used to think this way but saw the, proverbial, light. Why am I banging on so hard today? At Malt Blue, I have the joy of working on a wide range of freelance web application projects, both big and small.

However a recent project I took over gave me reason to pause. This project, had a lot going for it. It seemed to have had good intent with the basics of a meaningful design behind it. It had potential to be something really worthwhile. It could have been a maintainable project which wouldn’t have ended up costing the client quite a lot of money to support.

Unfortunately, a number of things were done wrong, the key being inconsistency. This led to a series of problems in the code, which I’ll summarize for the sakes of brevity. The are as follows:

  • Extremely time consuming to get to grips with the code base
  • Code was not intuitive or semantically meaningful
  • It was hard to see what linked to what – and more importantly – why
  • Time was required to be spent re-reading the same blocks repeatedly for understanding
  • Very difficult to tell where to find relevant sections of code

Here’s some examples of what was encountered:

  • The code base was littered with large swathes of commented out code
  • SQL queries were written using a DB abstraction layer, then later composed manually
  • Variables and configuration options were named “my”, “m”, “last” and so on
  • Multiple functions, with different names, in different modules performed nearly identical functionality
  • Operations were performed in segments of code, multiple layers deep, with no semantic direction

To cut a long story short, countless hours were spent, searching, tidying, documenting, trying almost in vain, to understand a code base needlessly.

If the earlier developers would have adhered to a coding standard, not to be confused with a coding style, a lot of this could have been avoided.

Now I know some people hate coding standards. But if they want to waste time, both theirs and others, I never want to work on their projects.

So find a standard which works for your business, your organization – you – and stick to it ardently. I don’t care which one you adhere to (within reason) – so long as you adhere to one.

There are a wide range of standards to choose from. Personally I use the Zend Framework coding standard as I primarily work on Zend Framework-based projects.

But if you have another one, such as Pear, GNU, Symfony, even WordPress, make sure you know why, or if you’re in a team, you’re all in agreement and then make sure you adhere to it.

Now that I’ve had a rant, here’s the benefits they provide:

Your Code is Easier to Read

When you use a standard, your code is readable, both to you and others. Why, because it’s consistent. Now, it might not be the best standard, but at least, in a short period of time, you will be able to follow the flow.

Take the following code for example. To some it may seem trivial. But if you imagine this throughout a code base (even with a formatter in an IDE or script) this code is hard to read. Let’s leave out the obvious spelling mistakes

/**
 * @var array
 */
protected $_messageTemplates = array(self::OBJECT_CATEGORY_NAME_EXISTS_INSERT => '"%value%" is already chooosen. Pleas select another.',
        self::OBJECT_CATEGORY_NAME_EXISTS_UPDATE => '"%value%" is already chooosen. Pleas select another.',
);

Your Code is Easier to Understand

This is perhaps the biggest point for me. Whether it’s the variable naming convention or otherwise, the intent of your code is easier to follow. Take the following example:

/**
 * @var array
 */
protected $_messageVariables = array(
        'nice1' => '_nice1',
        'nice2' => '_nice2'
);

//...

public function eventContact($value, $niceName, $params = null)
{
    $this->_nice1 = $params[0];
    $this->_nice2 = $params[1];
    $this->_setValue($value);
    if ($this->_value == '' && $this->_nice1 == '' && $this->_nice2 == '') {
        $this->_error(self::MISMATCH);
    }
    return self::$_instance;
}

I’m not a rocket scientist or a Rhodes scholar, but neither am I unintelligent. But I can’t infer what nice1 and nice2 are meant to be for.

Can you? What do you think the class it was in may have been doing? Here’s a tip, it was for validating contact information.

Your Code is Easier to Maintain

From a model class in the same code base, here’s another example:

final public function query($query)
{
    return $this->_db->query($query);
}

final public function select()
{
    return $this->_db->select();
}

final public function fetchAll($select)
{
    return $this->_db->fetchAll($select);
}

final public function fetchRow($select)
{
    return $this->_db->fetchRow($select);
}

final public function fetchPairs($select)
{
    return $this->_db->fetchPairs($select);
}

The class constructor initializes a protected member variable, _db, with the application database connection, which these functions use. However, they’re doing nothing more than wrapping internal functionality. Here is another example:

final class My_Enums_DateFormat {
    const MYSQL_DATE_TIME           = 'Y-m-d H:i:s';
    const MYSQL_DATE                = 'Y-m-d';
    const ADMIN_NICE                = 'j M Y h:i:s A';
    const DAY_MONTH_YEAR_HOUR_MIN_SEC   = 'd/m/Y H:i:s';
    const MONTH_DAY_YEAR_HOUR_MIN_SEC   = 'm/d/Y H:i:s';
    const MONTH_DAY_YEAR_HOUR_MIN_SEC_MERIDIAN  = 'm/d/Y h:i:s A';
    const DAY_MONTH_YEAR                = 'd/m/Y';
    const MONTH_DAY_YEAR                = 'm/d/Y';
    const HOUR                      = 'H';
    const MINUTE                    = 'i';
    const MERIDIAN                  = 'A';
    const SMALL_HOUR                = 'h';
    const FRONT_END_NICE            = 'F j, Y';
    const MYSQL_TIME                = 'H:i:s';
    const ADMIN_TIME                = 'h:i:s A';
    const TIME                      = 'g:i a';
    const TWENTY_FOUR_HOUR          = 'Hi';
    const DOWNLOAD_DATE             = 'Ymd';

    //...
}

This doesn’t strictly fall in to the above category – more in to the DRY. However, what is the purpose of writing code which replicates existing functionality, i.e., PHP DateTime, Zend Date et al? Why would you do this?

Why would you write functionality yourself which already exists, has a range of high quality unit tests, has had 10′s, 100′s or 1000′s of eyes on on it, verifying its quality, holding it up to scrutiny?

Please don’t do this – unless there’s a really good reason for it.

Your Code is Easier to Collaborate On

As a result of all of these points, code is harder to collaborate on. Why? If it’s hard for one person to work on a code base without wondering where errors might turn up, extrapolate it over a team of 2, 3, 5 or more.

With clean code and a clear and concise standard which’s adhered to, at the very least ensures if you’re going to write rubbish code, it’s clear rubbish.

When you don’t though, as I’m sure you don’t you’re well on your way to building high quality, maintainable code, now and in to the future.

What are Your Horror Stories?

You’ve heard mine, now I want to hear your worst experiences. What have you encountered? More importantly, what have you done about it? Was it too hard to overcome or was it manageable?

Share with us all in the comments today. The best (or is that worst) story gets a free copy of the next edition of PHP Architect magazine.

image copyright marsmet481

Software Engineering
  • harikt

    Hey Matthew,
     
    As you mentioned some coding standards to Zend, Pear, Symfony I would like to say the current standards these projects follow are the same now or in the near future .
     
    https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md
     
    https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md
     
    That means we have one standard for the PHP :-) . That will be awesome!
     
    Some of them are implementing the PSR-2 , http://www.php-fig.org/ ( I agree there are difference in opinion for PSR-2 for some projects like lithium, cake etc which will never follow according to my knowledge )

    • http://www.matthewsetter.com/ maltblue

      Thanks for the point about converging standards. I agree there’s debate about the latter PSR standards. But irrespective of the good and bad points about them, at least we’re collectively moving in a good direction. As a community we’re continually improving and doing what we do better and that’s always heartening to see.

  • http://www.ringcentral.com/voip-providers/index.html VOIP Provider

    I learned a lot from your post, thanks for sharing your ideas.

    • http://www.matthewsetter.com/ maltblue

      @VOIP Provider Not a problem at all. Very happy to help.