07/02 2007

Coding Standards, Comments and Documentation

When coding in any programming language it is very important to use proper coding standards. In a nutshell a coding standard is a definition for how to write code, name variables/objects and indent code so that it is structured and consistant. This has the benefit of making the code a lot easier to read and understand which helps in finding syntax errors and making modifications more quickly.

There are many widely used coding standards to choose from. The most common standards are called Allman/BSD and K&R, and the one I use when coding is Allman/BSD.

An example of some badly written code:

if($hours < 24 && $minutes < 60 && $seconds < 60) {return true;}
else{return false;}

The same code using Allman/BSD:

if($hours < 24 && $minutes < 60 && $seconds < 60)
{
return true;
}
else
{
return false;
}

Proper commenting and documentation can also make code easier to understand, especially if someone needs to understand code that was written by someone else. Without comments it can be very difficult to work out what code does and can dramatically affect the time required to make modifications to the code.

Example code:

// Store user information from the database into User objects in the users array
for($i=0; $i<$this->num_results; $i++)

{
$data = $result->getArray();
$this->users[$data['user_id'] = new User($data);
}

This comment tells the programmer exactly what this block of code does. Without it a programmer unfamiliar with the code might have to spend time going through it to work it out. There are also ways of producing much more comprehensive documentation, such as using JavaDoc or PHPDoc. These are tools which use special comments in your code to generate interactive documentation on all the objects, classes and variables it contains.

This article only covers the basics of coding standards and documentation. For more information about code and coding standards please visit these links:

back me up

No replies to “Coding Standards, Comments and Documentation”