Wednesday, February 07, 2007

Good Standards To Follow in PHP

In Software Development, most of the programmers have faced a very familiar situation of understanding other people codes for revamping or optimization. It's really challenging task to work in a maintenance project that demands cracking another programmers logic and thoughts. I equally love working in maintenance/optimization projects as like the new development projects. But as programmer I always strive hard to follow common standard while coding for a project. Coding style can vary by a bit for different project to avoid disinterest. Coding standards can be followed to maintain a consistent programming style throughout the core code base. If programmers follow guidelines it will be easier for others to understand and to maintain what has been developed if the project needs to optimized even after their stint.

I got sometime to work on finalizing standardizing the code styles that needs to be followed for future development... As these are very generic and can be useful for others I'm glad to share those.

Sections:
  • Naming Convention
  • Indentation/Tabs/Space Policy
  • Usage of Parens () with Key Words and Functions Policy
  • Control Structures
  • Function Calls
  • Function Definitions
  • Alignment of Declaration Blocks
  • No Magic Numbers
  • Comments
  • Others
  • Usage of ?:
  • Do Not Default If Test to Non-Zero
  • PHP Code Tags
  • Miscellaneous
Naming Convention

Class Names
  • Use upper case letters as word separators, lower case for the rest of a word
  • First character in a name is upper case
  • No underbars ('_')
  • When confronted with a situation where you could use an all upper case abbreviation instead use an initial upper case letter followed by all lower case letters. No matter what
Example
 class NameOneTwo

class Name

class GetHtmlStatistic

Method Names
  • Use the same rules as class
Example
 Connect()

GetData()

BuildSomeWidget()

Private class members
  • Class members that are intended to be used only from within the same class in which they are declared are preceded by a single underscore.
Example
 private $_mStatus

_Sort()

_InitTree()
Protected class members
  • Class members that are intended to be used only from within the same class in which they are declared or from subclasses that extend it are not preceded by a single underscore.

Example
 protected $mSomevar

protected function InitTree()

Class Attribute Names
  • Class member attribute names should be prefixed with the character 'm'
  • After the 'm' use the same rules as for class names
  • 'm' always precedes other name modifiers like 's' for static
Example
 $mVarAbc

$mErrorNumber

$msVolume

Method Argument Names
  • Methods argument names should be prefixed with the character 'a'
  • After the 'a' use the same rules as for class names
Example

function StartYourEngines($aSomeEngine, $aAnotherEngine, $aAgainOne)

Variable Names
  • Use all lower case letters
  • Use '_' as the word separator
Example
 $error

$an_example_for_var

Array Element
  • Array element names follow the same rules as a variable.
  • Use '_' as the word separator.
  • Don't use '-' as the word separator
  • Access an array's elements with single or double quotes
Example

$myarr['foo_bar'] = 'Hello';

Global Variables
  • Global variables should be prefixed with a 'g'
Example
 global $gLog

global $gTimeOut
Constants
  • Constants should always be all-uppercase, with underscores to separate words
  • Prefix constant names with the uppercased name of the class they are used in
Example
 GLOBAL_CONSTANT_FOR_EX
Static Variables
  • Static variables may be prefixed with 's'
Example
 static $msVolume

static $msVolume
Function Names
  • Use all lower case letters with '_' as the word delimiter
Example
 function some_function()
{
//code block
}
Indentation/Tabs/Space Policy
  • Indent using 4 spaces for each level
  • Do not use tabs, use spaces
Example
 function function()
{
if (something bad){
if (another thing bad){
while (more input){
}
}
}
}
Parens () with Key Words and Functions Policy
  • Do not put parens next to keywords. Put a space between
  • Do put parens next to function names
  • Do not use parens in return statements when it's not necessary
Example
 if (condition){
}

while (condition){
}

strcmp($s, $s1);

return 1;
Control Structures
  • These include if, for, while, switch, etc
  • Control statements should have one space between the control keyword and opening parenthesis, to distinguish them from function calls
  • Always use curly braces even in situations where they are technically optional. Having them increases readability and decreases the likelihood of logic errors being introduced when new lines are added.
Example
 if ((condition1) || (condition2)) {
action1;
} elseif ((condition3) && (condition4)) {
action2;
} else {
defaultaction;
}

switch (condition) {
case 1:{
action1;
break;
}
case 2:{
action2;
break;
}
default:{
defaultaction;
break;
}
}
Function Calls
  • Functions should be called with no spaces between the function name, the opening parenthesis, and the first parameter
  • Give single space between commas and each parameter, and no space between the last parameter, the closing parenthesis, and the semicolon
  • There should be one space on either side of an equals sign used to assign the return value of a function to a variable
Example
 foo($bar, $baz, $quux)

$short = foo($bar);

$long_variable = foo($baz);
Function Definitions
  • Arguments with default values go at the end of the argument list
  • Depends on where you are defining the function(Class or outside), use the appropriate naming convention
Example
 function connect($aDsn, $aPersistent = false)
{
return true;
}
Alignment of Declaration Blocks
  • Block of declarations should be aligned
Example
 var     $mDate

var& $mrDate

var& $mrName

var $mName


$mDate = 0;

$mrDate = NULL;

$mrName = 0;

$mName = NULL;

No Magic Numbers
  • A magic number is a bare-naked number used in source code. It's magic because no-one has a clue what it means including the author inside 3 months.
  • Instead of magic numbers use a real name that means something. You should use define() for example.
Bad Usage Example
 if (22 == $foo) {
start_thread();
} else if (19 == $foo) {
refund();
} else if (16 == $foo) {
infinite_loop();
}else {
blah_blah();
}
Correct Usage Example
 define("TIME_OUT", "22");
define("ROUND_UP", "19");
define("BREAK_DOWN", "16");

if (TIME_OUT == $foo) {
start_thread();
} else if (ROUND_UP == $foo) {
refund();
} else if (BREAK_DOWN == $foo) {
infinite_loop();
}else {
blah_blah();
}
Comments
  • Consider your comments a story describing the system.
  • Expect your comments to be extracted by a robot and formed into a man page.
  • Class comments are one part of the story, method signature comments are another part of the story, method arguments another part, and method implementation yet another part. All these parts should weave together and inform someone else at another point of time just exactly what you did and why.
Example
Comments at top of file:
 /*
* Short description for file
*
* Long description for file (if any)...
*
* @Module ModuleName
* @package PackageName
* @author Original Author
* @author Another Author
*/
Comments at top of class:
 /**
* Short description of class
*
* Long description of class (if any)...
* @Module ModuleName
* @package PackageName
*/
Comments at top of function:
 /**
* Short description of function
*
* Long description of function (if any)...
*
* @param $arg1 short description about first argument
* @param $arg1 short description about second argument
*
* @return short description what function will return
*
* @access specify the access type
* @static true/false
*/
function ShowResults($arg1, $arg2)
{
return 1;
}
Others

Usage of ?:
  • Put the condition in parens so as to set it off from other code
  • If possible, the actions for the test should be simple functions
  • Put the action for the then and else statement on a separate line unless it can be clearly put on one line
Example
 (condition) ? funct1() : func2();

(condition)
? long statement
: another long statement;
Do Not Default If Test to Non-Zero
  • Do not default the test for non-zero
Example
 if (FAIL != f())

is better than

if (f())
PHP Code Tags
  • Use standard approach to mark PHP codes like
Example
 <?php

?>
Miscellaneous
  • Do not do any real work in an object's constructor. Inside a constructor initialize variables only and/or do only actions that can't fail
  • There should be only one statement per line unless the statements are very closely related.
  • Always document a null body for a for or while statement so that it is clear that the null body is intentional and not missing code
Example
 while ($dest++ = $src++)
; // VOID
As usual comments are always welcome to discuss and make corrective measures.

1 comment: