Coding Standards


In the rush to get programming work done on time (or done at all), programmers often neglect their code and the need to keep it both legible and well documented. This section examines coding standards and some of the things to consider when writing them.

Worrying About Style

Programming is often a hectic business, with deadlines, design changes, and complicated solutions to complicated problems. As we try to solve a problem, we might insert some random code in an odd place or forget to comment a complicated function, or somebody else working on the file might have a different coding style from us. Entropy creeps into scripts, the net result of which can be something like the following:

   public function userNameExists($nm,&$unexists,$c)   { if ($nm == '') throw new InvalidArgumentException();     // joe: get con     if ($db_c == NULL) {       $c = $this->getConnection();     } else {                $c = $db_c;     }     $name = $c->real_escape_string($nm);     $qstr = <<<EOQUERY     SELECT user_name FROM users WHERE user_name = '$nm' EOQUERY;     $results = $c->query($qstr);     if ($results === FALSE)         {         $c->close(); return ERR_INTERNAL_DB_ERROR;         }     $unexists = FALSE;     while (($row = $results->fetch_assoc()) !== NULL) {       if ($row['user_name'] == $nm)       {         $unexists = TRUE;         break;         }     } $results->close();     if ($db_c === NULL) $c->close();     return TRUE;   } 

Before you scoff and suggest that code could not possibly get that bad, many a programmer who has worked on a large and uncoordinated project can assure you in no uncertain terms that this is actually only "middle of the road" in terms of ugliness. Much worse exists, and it is usually a nightmare to maintain, interpret, or take over when the original programmer(s) quit or move on to new projects.

In addition to inconsistent coding style and poor variable names, this code contains almost no documentation. Even if the programmers working on it are stunningly smart and able to figure out how it works all of the time, other people forced to look at the code, such as testers, documentation authors, or even clients, will likely run screaming.

Apart from artistic value, however, some argue that not much compels us to write code that is a beauty to behold. We argue that this is a dangerous assumption, one that can lead to problems later on in development:

  • Illegible code is difficult to maintain. If somebody new comes to look at the code and sees something like if ($x === $xxx and ($y = $yxx) == $z), the person is going to have to spend a large amount of time deciphering what this means.

  • As programmers, we are not perfect (sadly), and it can be extremely frustrating to go back and look at a piece of code we wrote weeks, months, or even years before, and have absolutely no idea what it means or how it works.

  • Some of the documentation for our system can be gleaned by looking at the code involved, or at least the scripts can help those writing documentation understand exactly how something is supposed to work. If nobody can figure out what the code does, it is that much harder to describe how the system works.

Developing a Coding Standards Document

With all of this in mind, it certainly behooves us to write a coding standards document. This document does not need to be more than a couple of pages long (although some can grow to be as long as hundreds of pages, for the truly particular). It should specify clearly and unambiguously the style of coding you, as an individual or team, want to see the project use.

Some of the things to include in the coding standards document could include the following:

  • How to comment code and what style of comments to use.

  • Whether to use spaces and tab characters, and what indent level to use. The latter is the number of spaces to indent new lines. Some editors/integrated environments also let you set the number of spaces to which a tab character is equivalentthe default is usually eight.

  • What style of brackets to use around blocks of code associated with if, while, or for statements.

  • How to name parameters.

  • Which style of error handling should be used in scripts.

  • How to include other files or scripts within yours.

  • How to structure classes, and where to put data and member functions.

As a most basic example, you can just create a sample source code file that people can use as a template for their own files:

 <?php     // no short tags! //=---------------------------------------------------------= // filename.php //=---------------------------------------------------------= // Please put a description of the file here. // // Author: Put the original author's name here, along with //         his e-mail address. // // Use this style of comments. // - USE SPACES INSTEAD OF TABS --- ** NO TAB CHARACTERS ** // - USE INDENT LEVEL OF 2 SPACES. // - WRAP LINES at 76 characters. // // Put included files at the top.  Use require_once wherever // possible! // require_once('../lib/somefile.inc'); // // session and output buffering should go here: // session_start(); ob_start(); // // To declare a class, put member variables at the top, and // then put member functions in the following order: //      - public //      - protected //      - private // // Describe what the class does // class ClassName {   //   // describe what the variable is for   //   public $varName;     // use camel-casing of names.   //   // private vars go next   //   private $otherVarName = 'Oink';   //   // For member functions, include a description of what the   // function is for, what parameters it takes, and what   // any return values are !!!  Use in_, out_, inout_   // prefixes when possible.   //   // Parameters:   // $in_username            - user name.   // &$out_userid            - returned user ID   //   public function getUserName($in_username, &$out_userid)   {     //     // use type-specific comparisons === for NULL and FALSE.     // use the following style of brackets:     //     if ($in_username === NULL)     {       //       // use exceptions wherever possible.       //       throw new ArgumentException('$in_username NULL');     }     //     // use meaningful variable names!     //     $user_names = getarray();     //     // use foreach loops for arrays whenever possible!     //     foreach ($user_names as $userid => $name)     {       //       // even for single lines, use { and } please.       //       if ($name == $in_username)       {         return $userid;       }     }     throw new UserNotFoundException("$in_username");   } } // // place all script outside of functions and classes at // the end of the script. // // USE XHTML instead of just plain HTML. ?> <!DOCTYPE html PUBLIC "~//W3C//DTD XHTML 1.0 Transitional//EN"   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> etc ... 

Under no circumstances is it necessary that your coding standards look like this or specify the same conventions. Programming is a very individualistic tasksome would even argue an art formand there is nothing compelling you and your team of fellow developers to use any particular style. As long as everybody is using the same one and is comfortable with it, you have gone a long way toward keeping your scripts manageable.

Holy Wars

One of the problems with individualistic programmers and their art is that they tend to get extremely attached to a particular style, or school of art, as it were. People will end up quite irate at the mere suggestion of a block of code being written as

 for ($x = 0; $x < 100; $x++) {   if ($y === $x       and $date == $today       and $moon == 'full')   {     break;   } } 

when any fool with half a brain knows that true coders write their scripts as follows:

 for ($x = 0; $x < 100; $x++) {   if ($y === $x && $date == $today && $moon == 'full') {     break;   } } 

These debates over so-called programming religion can become quite heated and tend to be a waste of time. When all is said and done, it does not matter which style of coding you use. Programmers who begin working on a project with a style slightly different from that to which they are accustomed will typically find within a few weeks that the new style feels perfectly normal. Those who program for a living and work on many different projects have probably worked on a large number of different styles and can switch between them with ease.

As mentioned before, it does not matter which style you use as long as you are consistent about it in all of the files across a project.

Other Considerations

An increasingly popular concept is to use code as a primary source of documentation for classes or libraries. You can associate a number of different comment formats with class functions, or even regular functions, from which special tools can then come along and generate documentation. Classes that belong to the PHP Extension and Application Repository (PEAR), mentioned in Chapter 28, "Using PEAR," use a style of coding first seen with the Java programming language known as JavaDoc.

In this style, you can use specific tags to aid in documentation, which a tool then processes to generate documentation, often in HTML or even XML format:

 /**  * This is an example of a JavaDoc-style comment associated  * with a class function.  This text at the beginning  * describes how the function works, along with any other  * interesting notes.  You can then include information about  * parameters and return values.  *  * @param $in_username    The name of the user whose ID we  *                        wish to find.  * @param &$out_userid    The user ID associated with that  *                        username, or -1 on failure.  */ public function get_id($in_username, &$out_userid) {   // etc. } 

If you do want to use one of these documentation formats, you should ensure this is mentioned in your coding standards document.

Finally, no set of coding standards is useful unless it's actually followed. Code reviews (which are a good idea in and of their own to help find bugs and mentor younger programmers) and gentle prodding can prove surprisingly effective at encouraging people to keep their code legible.




Core Web Application Development With PHP And MYSQL
Core Web Application Development with PHP and MySQL
ISBN: 0131867164
EAN: 2147483647
Year: 2005
Pages: 255

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net