Wednesday, February 4, 2015

Coding Standards

Coding standards are important in any development project, but they are particularly important when many developers are working on the same project. Coding standards help ensure that the code is high quality, has fewer bugs, and can be easily maintained.

Following rules can be used for Core Development Projects (for Framework or Core PHP Development)

1. Indentation
Indentation should consist of 4 spaces. Tabs are not allowed.

Why
  • Gives the author, not the editor, control over the visual indentation.
  • It's important to emphasize the difference between indentation (tabs) and alignment (space). Trouble begins when developers use tabs for alignment.
  • Tabs may look the same as spaces in the editor but they do not behave the same.
  • Tabs may not necessarily behave the same across different editors, but spaces always will.
  • Consistent code viewing on any platform: web, desktop or print
  • It makes code easy to copy and paste for online discussion and sharing since most online viewers render Tab Characters as 4 spaces or more.

To clarify Take a quick look at the following images

Code with tabs (single character per tab equal to 4 spaces):

Code with tabs (single character per tab equal to 2 spaces): Nothing lineup anymore


2. Lines

2.1 Line Length
Target line length should be maximum 80 characters. However, longer lines are acceptable in some (rare) circumstances. Maximum length of any line of PHP code is 120 chars. Line longer then 80 characters SHOULD be split into multiple subsequent line.

Why
This is nothing to do with the monitor screen or editors limitations to display lengthy code lines but some valid reasons to get more details read the following interesting article

2.2 There MUST NOT be trailing whitespace at the end of non-blank lines.

2.3 There MUST NOT be more than one statement per line.

2.4 Blank lines MAY be added to improve readability and to indicate related blocks of code.

3. PHP Tag
Only <?php ?> is allowed to delimit the PHP code.

Why
Other style of tags are either deperacted or configuration dependend
Tip: Closing tag '?>' can be omitted in pure PHP script to avoide any unecesary white space injunction.

4. Naming Conventions

4.1 Constants
Constants should always be all-uppercase with underscore to seperate words. Prefix constant name with the uppercased name of the class / package they are used in.

To define global constant use
define('<CONSTANT_NAME>', <'value'>);

To define class constant use
class MyClass {
const <CONSTANT_NAME> = <'value'>;
}

e.g
const DB_DATASOURCE_NAME = 'mysql'; // constant of Db class
const SERVICES_AMAZON_S3_LICENSEKEY = 'xxxx'; // constant of Service class
define('PAGE_LIMIT', 10); // global constant

4.2 Variables
Variable name must start with a lowercase letter and follow the camelCaps convention.

For global, local and public class variables following rules apply.
Variables names may only contain alphanumeric characters. Underscore are not permitted. Numbers are permitted but discouraged.

For private and protected class variables first character must be a underscore "_" rest will be alphanumeric and follow camelCaps convention.

Verbosity is generally encouraged. Variables should always be as verbose as practical to describe the data that the developer intends to store in them. Terse variable names such as "$i" and "$n" are discouraged for all but the smallest loop contexts.

e.g.
$featuredNews = xxxx; // normal variable
private $isAbnormal; // class variable

4.3 Class Name
Classes should be given descriptive names. Avoid using abbreviations where possible. Class names should always begin with an uppercase letter. Each new word must be capitalized. The class hierarchy is also reflected in the class name, each level of the hierarchy separated with a single underscore

e.g
Log // single word class without package
ContentMetadata // multi word class
Vehical_Car //
Vehical_Bike //

4.4 Function Name
Function names may only contain alphanumeric characters. Underscores are not permitted. Numbers are permitted in function names but are discouraged in most cases.

Function names must always start with a lowercase letter. When a function name consists of more than one word, the first letter of each new word must be capitalized (camelCase).

For private and protected class functions name must start with an underscore. This is the only acceptable exceptions in a function name.

Verbosity is generally encouraged. Function names should be as verbose as is practical to fully describe their purpose and behavior.

Functions in the global scope (a.k.a "floating functions") are permitted but discouraged in most cases. Consider wrapping these functions in a static class.

e.g.
filterInput()
getElementById()
widgetFactory()
public doCalculations($param);
5. Class Definitions
  • Classes must be named according to naming conventions (refer 4.3)
  • Brace should always be on the line underneath the class name.
  • Every class must have a documentation block that confirms to the PHPDocumentor standard.
  • Only one class is permitted in each PHP file.
  • Placing additional code in class files is not permitted except includes.

e.g.
/**
documentation block
*/
class SampleClass
{
// content of class
}


Classes that extend other classes or which implement interfaces

class SampleClass extends FooAbstract implements BarInterface
{
// content of class
}

If as a result of such declarations, the line length exceeds the maximum line length, break the line before the "extends" and/or "implements" keywords, and pad those lines by one indentation level.

class SampleClass
extends FooAbstract
implements BarInterface
{
// content of class
}

6. Function Definition
  • Functions must be named according to naming convention (refer 4.4)
  • Functions / Methods inside classes must always declare there visibility by using private, protected or public modifiers.
  • the brace should always be written on the line underneath the function name
  • Space between the function name and the opening parenthesis for the arguments is not permitted.
  • Arguments with default values go at the end of argument list.
  • Always attempt to return a meaningful value.
  • Function arguments should be seperated by a single trailing space after the comma delimiter.

e.g.
function connect($dsn, $persistent = false)
{
if (is_array($dsn)) {
$dsninfo = &$dsn;
} else {
$dsninfo = DB::parseDSN($dsn);
}

if (!$dsninfo || !$dsninfo['phptype']) {
return $this->raiseError();
}

return true;
}

Functions with many parameters may need to be split onto several lines to keep the 80 characters/line limit. The first parameters may be put onto the same line as the function name if there is enough space. Subsequent parameters on following lines are to be indented 4 spaces. The closing parenthesis and the opening brace are to be put onto the next line, on the same indentation level as the "function" keyword.

function someFunctionWithAVeryLongName($firstParameter = 'something', $secondParameter = 'booooo',
$third = null, $fourthParameter = false, $fifthParameter = 123.12,
$sixthParam = true
) {
//....
}

7. Class Member Variables
  • Member variables must be named according to naming conventions (refer 4.2)
  • var construct is not permitted
  • Member variables declare there visibility by using private, protected or public modifiers.
  • Any variable declared in a class must be listed at the top of the class, above the declaration of any methods
  • Giving access to member variables directly by declaring them as public is permitted but discouraged in favor of accessor methods (set & get).

8. Function Calls
Functions should be called with no spaces between the function name, the opening parenthesis, and the first parameter; spaces between commas and each parameter, and no space between the last parameter, the closing parenthesis, and the semicolon.

e.g.
$var = foo($bar, $baz, $quux);

The CS require lines to have a maximum length of 80 chars. Calling functions or methods with many parameters while adhering to CS is impossible in that cases. It is allowed to split parameters in function calls onto several lines.

$this->someObject->subObject->callThisFunctionWithALongName(
$parameterOne, $parameterTwo,
$aVeryLongParameterThree
);



$this->someObject->subObject->callThisFunctionWithALongName(
$this->someOtherFunc(
$this->someEvenOtherFunc(
'Help me!',
array(
'foo' => 'bar',
'spam' => 'eggs',
),
23
),
$this->someEvenOtherFunc()
),
$this->wowowowowow(12)
);


9. Control Structure
The general style rules for control structures are as follows:



  • There MUST be one space after the control structure keyword

  • There MUST NOT be a space after the opening parenthesis

  • There MUST NOT be a space before the closing parenthesis

  • There MUST be one space between the closing parenthesis and the opening brace

  • The structure body MUST be indented once

  • The closing brace MUST be on the next line after the body

  • The body of each structure MUST be enclosed by braces. This standardizes how the structures look, and reduces the likelihood of introducing errors as new lines get added to the body.

9.1 if, elseif, else
Note the placement of parentheses, spaces, and braces; and that else and elseif are on the same line as the closing brace from the earlier body.

<?php

if ($expr1) {

// if body

} elseif ($expr2) {

// elseif body

} else {

// else body;

}

9.2 switch, case

A switch structure looks like the following. Note the placement of parentheses, spaces, and braces. The case statement MUST be indented once from switch, and the break keyword (or other terminating keyword) MUST be indented at the same level as the case body. There MUST be a comment such as // no break when fall-through is intentional in a non-empty case body.

<?php

switch ($expr) {

case 0:

echo 'First case, with a break';

break;

case 1:

echo 'Second case, which falls through';

// no break

case 2:

case 3:

case 4:

echo 'Third case, return instead of break';

return;

default:

echo 'Default case';

break;

}

9.3 while, do while

A while statement looks like the following. Note the placement of parentheses, spaces, and braces.



<?php

while ($expr) {

// structure body

}



Similarly, a do while statement looks like the following. Note the placement of parentheses, spaces, and braces.



<?php

do {

// structure body;

} while ($expr);



9.4 for

A for statement looks like the following. Note the placement of parentheses, spaces, and braces.



<?php

for ($i = 0; $i < 10; $i++) {

// for body

}



9.5 foreach

A foreach statement looks like the following. Note the placement of parentheses, spaces, and braces.



<?php

foreach ($iterable as $key => $value) {

// foreach body

}



9.6 try, catch


A try catch block looks like the following. Note the placement of parentheses, spaces, and braces.

<?php

try {

// try body

} catch (FirstExceptionType $e) {

// catch body

} catch (OtherExceptionType $e) {

// catch body

}

Note:
Long if statements may be split onto several lines when the character/line limit would be exceeded. The conditions have to be positioned onto the following line, and indented 4 characters. The logical operators (&&, ||, etc.) should be at the beginning of the line to make it easier to comment (and exclude) the condition. The closing parenthesis and opening brace get their own line at the end of the conditions.
Keeping the operators at the beginning of the line has two advantages: It is trivial to comment out a particular line during development while keeping syntactically correct code (except of course the first line). Further is the logic kept at the front where it's not forgotten. Scanning such conditions is very easy since they are aligned below each other.

if (($condition1
|| $condition2)
&& $condition3
&& $condition4
) {
//code here
}

$is_foo = ($condition1 || $condition2);
$is_bar = ($condition3 && $condtion4);

if ($is_foo && $is_bar) {
// ....
}

10. Keywords and True/False/Null

PHP keywords MUST be in lowercase. The PHP constants true, false, and null MUST be in lower case.

11. Code Readability

11.1 every assignment or comparison oprations must preceed and follow with a space

e.g.
$rows=1; // wrong
$rows = 1; // correct

11.2 the equal signs may be aligned in block-related assignments:

$short = foo($bar);
$longer = foo($baz);

The rule can be broken when the length of the variable name is at least 8 characters longer/shorter than the previous one:

$short = foo($bar);
$thisVariableNameIsVeeeeeeeeeeryLong = foo($baz);

Split long assignments onto several lines

Assignments may be split onto several lines when the character/line limit would be exceeded. The equal sign has to be positioned onto the following line, and indented by 4 characters.

$GLOBALS['TSFE']->additionalHeaderData[$this->strApplicationName]

= $this->xajax->getJavascript(t3lib_extMgm::siteRelPath('nr_xajax'));

11.3 Array assignments

Non Associative

$days = array(1, 2, 3, 4, 5, 6, 7);
or if not fit in line
$months = array(
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'June',
'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec',
);

Associative Array

$some_array = array(
'foo' => 'bar',
'spam' => 'ham',
);


  1. 12. Comments

12.1 Documentable comments
Inline documentation comment blocks (docblocks) must be provided. All blocks must be compatible with phpDocumentor format.
Follwoing docblocks are mendatory with the specified formats. However extra doctags (which are allowed as per phpDocumentor) can be used.
12.1.1 File docblock
every php file must have this block at the start of the file.
/**
* Short description for file
*
* Long description for file (if any)...
*/


12.1.2 Class docblock
Every class must have this block above the class definition
/**
* Short description for class
*
* Long description for class (if any)...
*/
12.1.3 Function docblock
Every function must have this block above the function defination
/**
* description for function
*
* @access
* @param
* @return
*/


12.2 Non Documentable comments
Non-documentation comments are strongly encouraged and Only following style of syntex are allowed. Non documentation comments are for small blocks of code describing what that block of code is doing.
/* */ and //
Note: avoid obvious comments

// get the country code
$country_code = get_country_code($_SERVER['REMOTE_ADDR']);
// if country code is US
if ($country_code == 'US') {
// display the form input for state
echo form_input_state();
}

can be rewritten as

// display state selection for US users
$country_code = get_country_code($_SERVER['REMOTE_ADDR']);
if ($country_code == 'US') {
echo form_input_state();
}
  1. 13. E_STRICT-compatible code

This means that php script must not produce any warnings or errors when PHP's error reporting level is set to E_ALL | E_STRICT.

14. Deprecated Code
Deprecated Features of PHP should not be used. Depends on which version of PHP is applicable for the project.




No comments:

Post a Comment