Coding Style Coding Style

Requirements of making your code readable

This is an archived version of the document. The current version is here.

 

Part of the first version of this document was merely taken from “phpBB3 Coding Guidelines” and adapted. Thanks to their authors for strong coding style and description they provided to it.

Now it's updated to cover not only coding standards itself used in Cotonti but standards for working with files within project.

Nevertheless this document still do not cover theme of choosing IDE for development, it's setup and configuration or using some code styling tools. But you can see some info about it here and check helpful links in the bottom og this page.

#1. General rules

This common rules consider all source code files in the project (HTML, PHP, CSS, JS, etc.) if other is not defined.

  • Code should be in UTF-8

  • A new line should be LF.

  • Indentation should be tabs

  • No extra spaces at the end of lines (set up your text editor, so that it removes extra spaces when saving).

    Each line of text in your code should be at most 100 characters long.  Put the line break wherever it makes the most aesthetic sense, not necessarily the breaking point closest to 100 characters.

 

#1.1. Editor Settings

Tabs vs Spaces:
In order to make this as simple as possible, we will be using tabs, not spaces. We enforce 4 (four) spaces for one tab - therefore you need to set your tab width within your editor to 4 spaces. Make sure that when you save the file, it's saving tabs and not spaces. This way, we can each have the code be displayed the way we like it, without breaking the layout of the actual files.
Tabs in front of lines are no problem, but having them within the text can be a problem if you do not set it to the amount of spaces every one of us uses. Here is a short example of how it should look like:

 

{TAB}$mode{TAB}{TAB}= request_var('mode', '');
{TAB}$search_id{TAB}= request_var('search_id', '');

If entered with tabs (replace the {TAB}) both equal signs need to be on the same column.

Linefeeds:
Ensure that your editor is saving files in the UNIX-style linefeed format. This means lines are terminated with a LF, not with CR/LF (Windows) or CR (Mac). Any decent editor should be able to do this, but it might not always be the default. Know your editor. If you want advice on Windows text editors, just ask one of the developers. Some of them do their editing on Windows. A plugin to show and change the EOL type in Netbeans can be found here.

If you are using `Git` in your development process — it can be configured to maintain linefeeds by its own.

 

#2. PHP guidelines

#2.1. A brief view

…in addition to general rules:

  • Use PHPDoc
  • Omit closing PHP tag `?>`
  • As a rule, use single quotes, (such as 'string'), not double quotes ("string").
  • Curly braces split with new lines.
  • Use space liberally, use empty lines to separate logical chunks of code.
  • Use spaces around arithmetic operators, e.g. (1 + 2) not (1+2).
  • Use spaces around braces.
  • Use spaces after commas (",").

#2.2. File Header

All PHP files should contain some documentation info formatted as PHPDoc.

Standard header for new files:
This template of the header must be included at the start of all Cotonti files:

/** 
*
* @package {PACKAGENAME}
* @version {VERSION}
* @copyright (c) 2008 Cotonti Team 
* @license BSD License
*
*/

If you are developing some extension, you do not need to define `@version` tag as version info already set in extension setup file and may confuse other developers.

Files containing inline code:
For those files you have to put an empty comment directly after the header to prevent the documentor assigning the header to the first code element found.

/**
* {HEADER}
*/

/**
*/
{CODE}

 

Files containing only functions:
Do not forget to comment the functions (especially the first function following the header). Each function should have at least a comment of what this function does. For more complex functions it is recommended to document the parameters too.

Files containing only classes:
Do not forget to comment the class. Classes need a separate @package definition, it is the same as the header package name. Apart from this special case the above statement for files containing only functions needs to be applied to classes and it's methods too.
Code following the header but only functions/classes file:
If this case is true, the best method to avoid documentation confusions is adding an ignore command, for example:

/** 
* {HEADER}
*/

/**
* @ignore
*/
Small code snipped, mostly one or two defines or an if statement

/**
* {DOCUMENTATION}
*/
code...

#2.3. Variable/Function Naming

We will not be using any form of hungarian notation in our naming conventions. Many of us believe that hungarian naming is one of the primary code obfuscation techniques currently in use.

Variable Names:
Variable names should be in all lowercase, with words separated by an underscore, example:
$current_user is right, but $currentuser and $currentUser are not.
Names should be descriptive, but concise. We don't want huge sentences as our variable names, but typing an extra couple of characters is always better than wondering what exactly a certain variable is for.

Loop Indices:
The only situation where a one-character variable name is allowed is when it's the index for some looping construct. In this case, the index of the outer loop should always be $i. If there's a loop inside that loop, its index should be $j, followed by $k, and so on. If the loop is being indexed by some already-existing variable with a meaningful name, this guideline does not apply, example:

for ($i = 0; $i < $outer_size; $i++)
{
   for ($j = 0; $j < $inner_size; $j++)
   {
      foo($i, $j);
   }
}

 

Function Names:
Functions should also be named descriptively. We're not programming in C here, we don't want to write functions called things like "stristr()". Again, all lower-case names with words separated by a single underscore character. Function names should preferably have a verb in them somewhere. Good function names are print_login_status(), get_user_data(), etc.

In Cotonti we are used to standard `cot_` prefix for any function to avoid naming conflicts. It is standard for the core API to be reusable, but you are not forced for `cot_` prefix in your plugins, unless those functions are going to be reused as the core API. You can use your own prifx within your extension API.

Function Arguments:
Arguments are subject to the same guidelines as variable names. We don't want a bunch of functions like: do_stuff($a, $b, $c). In most cases, we'd like to be able to tell how to use a function by just looking at its declaration.

Summary:
The basic philosophy here is to not hurt code clarity for the sake of laziness. This has to be balanced by a little bit of common sense, though; print_login_status_for_a_given_user() goes too far, for example -- that function would be better named print_user_login_status(), or just print_login_status().
 

#2.4. Code Layout

Always include the braces:
This is another case of being too lazy to type 2 extra characters causing problems with code clarity. Even if the body of some construct is only one line long, do not drop the braces. Just don't, examples:
These are all wrong:

if (condition) do_stuff();
if (condition)
        do_stuff();

while (condition)
        do_stuff();

for ($i = 0; $i < size; $i++)
        do_stuff($i);

 

These are all right.

if (condition)
{
        do_stuff();
}

while (condition) 
{
        do_stuff();
}

for ($i = 0; $i < size; $i++) 
{
        do_stuff();
}

 

Where to put the braces:
This one is a bit of a holy war, but we're going to use a style that can be summed up in one sentence: Braces always go on their own line. The closing brace should also always be at the same column as the corresponding opening brace, examples:

 

if (condition) 
{
        while (condition2)
        {
                ...
        }
}
else 
{
        ...
}

for ($i = 0; $i < $size; $i++) 
{
        ...
}

while (condition) 
{
        ...
}

function do_stuff() 
{
        ...
}

 

Use spaces between tokens:
This is another simple, easy step that helps keep code readable without much effort. Whenever you write an assignment, expression, etc.. Always leave one space between the tokens. Basically, write code as if it was English. Put spaces between variable names and operators. Don't put spaces just after an opening bracket or before a closing bracket. Don't put spaces just before a comma or a semicolon. This is best shown with a few examples, examples:

// Each pair shows the wrong way followed by the right way. 
$i=0;
$i = 0;
                
if($i<7) ...
if($i < 7) ...
                
if( ($i < 7)&&($j > 8) ) ...
if($i < 7 && $j > 8) ...
                
do_stuff( $i, 'foo', $b );
do_stuff($i, 'foo', $b);
                
for($i=0; $i<$size; $i++) ...
for ($i = 0; $i < $size; $i++) ... 
                
$i=($j < $size)?0:1;
$i = ($j < $size) ? 0 : 1;

 

Operator precedence:
Do you know the exact precedence of all the operators in PHP? Neither do I. Don't guess. Always make it obvious by using brackets to force the precedence of an equation so you know what it does. Remember to not over-use this, as it may harden the readability. Basically, do not enclose single expressions. Examples:

// what's the result? who knows. 
$bool = ($i < 7 && $j > 8 || $k == 4);
        
// now you can be certain what I'm doing here.
$bool = (($i < 7) && (($j < 8) || ($k == 4)));
        
// But this one is even better, because it is easier on the eye but the intention is preserved
$bool = ($i < 7 && ($j < 8 || $k == 4));

Quoting strings:
There are two different ways to quote strings in PHP - either with single quotes or with double quotes. The main difference is that the parser does variable interpolation in double-quoted strings, but not in single quoted strings. Because of this, you should always use single quotes unless you specifically need variable interpolation to be done on that string. This way, we can save the parser the trouble of parsing a bunch of strings where no interpolation needs to be done.
Also, if you are using a string variable as part of a function call, you do not need to enclose that variable in quotes. Again, this will just make unnecessary work for the parser. Note, however, that nearly all of the escape sequences that exist for double-quoted strings will not work with single-quoted strings. Be careful, and feel free to break this guideline if it's making your code easier to read, examples:
wrong:

$str = "This is a really long string with no variables for the parser to find.";
do_stuff("$str");

right:

$str = 'This is a really long string with no variables for the parser to find.';
do_stuff($str);
// Sometimes single quotes are just not right
$post_url = $phpbb_root_path . 'posting.' . $phpEx . '?mode=' . $mode . '&amp;start=' . $start;
        
// Double quotes are sometimes needed to not overcroud the line with concentinations
$post_url = "{$phpbb_root_path}posting.$phpEx?mode=$mode&amp;start=$start";

 

 

In SQL Statements mixing single and double quotes is partly allowed (following the guidelines listed here about SQL Formatting), else it should be tried to only use one method - mostly single quotes.

Associative array keys:
In PHP, it's legal to use a literal string as a key to an associative array without quoting that string. We don't want to do this -- the string should always be quoted to avoid confusion. Note that this is only when we're using a literal, not when we're using a variable, examples:

 

// wrong
$foo = $assoc_array[blah];
        
// right 
$foo = $assoc_array['blah'];
        
// wrong
$foo = $assoc_array["$var"];
        
// right 
$foo = $assoc_array[$var];

 

Comments:
Each complex function should be preceded by a comment that tells a programmer everything they need to know to use that function. The meaning of every parameter, the expected input, and the output are required as a minimal comment. The function's behaviour in error conditions (and what those error conditions are) should also be present - but mostly included within the comment about the output.

Especially important to document are any assumptions the code makes, or preconditions for its proper operation. Any one of the developers should be able to look at any part of the application and figure out what's going on in a reasonable amount of time.

Avoid using /* */ comment blocks for one-line comments, // should be used for one/two-liners.

Magic numbers:
Don't use them. Use named constants for any literal value other than obvious special cases. Basically, it's ok to check if an array has 0 elements by using the literal 0. It's not ok to assign some special meaning to a number and then use it everywhere as a literal. This hurts readability AND maintainability. The constants true and false should be used in place of the literals 1 and 0 -- even though they have the same values (but not type!), it's more obvious what the actual logic is when you use the named constants. Typecast variables where it is needed, do not rely on the correct variable type (PHP is currently very loose on typecasting which can lead to security problems if a developer does not have a very close eye to it).

Shortcut operators:
The only shortcut operators that cause readability problems are the shortcut increment $i++ and decrement $j-- operators. These operators should not be used as part of an expression. They can, however, be used on their own line. Using them in expressions is just not worth the headaches when debugging, examples:
wrong:

$array[++$i] = $j;
$array[$i++] = $k;

 

right:

$i++;
$array[$i] = $j;

$array[$i] = $k;
$i++;

 

Inline conditionals:
Inline conditionals should only be used to do very simple things. Preferably, they will only be used to do assignments, and not for function calls or anything complex at all. They can be harmful to readability if used incorrectly, so don't fall in love with saving typing by using them, examples:

 

// Bad place to use them
($i < $size && $j > $size) ? do_stuff($foo) : do_stuff($bar);
        
// OK place to use them 
$min = ($i < $j) ? $i : $j;

 

Don't use uninitialized variables.
We recommend using a higher level of run-time error reporting. This will mean that the use of an uninitialized variable will be reported as a warning. These warnings can be avoided by using the built-in isset() function to check whether a variable has been set - but preferably the variable is always existing. For checking if an array has a key set this can come in handy though, examples:

// Wrong 
if ($forum) ...
        
// Right 
if (isset($forum)) ...
        
// Also possible
if (isset($forum) && $forum == 5)

 

The empty() function is useful if you want to check if a variable is not set or being empty (an empty string, 0 as an integer or string, NULL, false, an empty array or a variable declared, but without a value in a class). Therefore empty should be used in favor of isset($array) && sizeof($array) > 0 - this can be written in a shorter way as !empty($array).

Switch statements:
Switch/case code blocks can get a bit long sometimes. To have some level of notice and being in-line with the opening/closing brace requirement (where they are on the same line for better readability), this also applies to switch/case code blocks and the breaks. An example:
Wrong:

switch ($mode)
{
        case 'mode1':
                // I am doing something here
                break;
        case 'mode2':
                // I am doing something completely different here
                break;
}

 

Good

 

switch ($mode)
{
        case 'mode1':
                // I am doing something here
        break;

        case 'mode2':
                // I am doing something completely different here
        break;

        default:
                // Always assume that the case got not catched
        break;
}

 

Even if the break for the default case is not needed, it is sometimes better to include it just for readability and completeness.

 

#2.5. SQL/SQL Layout

SQL code layout:
SQL Statements are often unreadable without some formatting, since they tend to be big at times. Though the formatting of sql statements adds a lot to the readability of code. SQL statements should be formatted in the following way, basically writing keywords:

$sql = "SELECT * 
<-one tab->FROM $db_table_name 
<-one tab->WHERE a = 1 
<-two tabs->AND (b = 2 
<-three tabs->OR b = 3) 
<-one tab->ORDER BY b";

 

Here the example with the tabs applied:

$sql = "SELECT * 
        FROM $db_table_name 
        WHERE a = 1 
                AND (b = 2 
                        OR b = 3) 
        ORDER BY b";

 

SQL Quotes:
Double quotes where applicable (The variables in these examples are typecasted to integers before) ... examples:

// These are wrong.
"UPDATE " . SOME_TABLE . " SET something = something_else WHERE a = $b"; 
'UPDATE ' . SOME_TABLE . ' SET something = ' . $user_id . ' WHERE a = ' . $something;
        
// These are right. 
"UPDATE $db_table_name SET something = something_else WHERE a = $b"; 
"UPDATE $db_table_name SET something = $user_id WHERE a = $something";

 

In other words use single quotes where no variable substitution is required or where the variable involved shouldn't appear within double quotes. Otherwise use double quotes.

Avoid DB specific SQL:
The "not equals operator", as defined by the SQL:2003 standard, is "<>"

 

// This is wrong.
$sql = "SELECT * 
        FROM $db_table_name 
        WHERE a != 2";
        
// This is right. 
$sql = "SELECT * 
        FROM $db_table_name 
        WHERE a <> 2";

 

Common functions:
$db->prep():
Always use $db->prep() if you need to check for a string within an SQL statement (even if you are sure the variable cannot contain single quotes - never trust your input), for example:

$sql = "SELECT *
        FROM $db_table_name
        WHERE username = '" . $db->prep($username) . "'";

 

#2.6. Optimizations

Operations in loop definition:
Always try to optimize your loops if operations are going on at the comparing part, since this part is executed every time the loop is parsed through. For assignments a descriptive name should be chosen. Example:

 

// On every iteration the sizeof function is called
for ($i = 0; $i < sizeof($post_data); $i++)
{
        do_something();
}
        
// You are able to assign the (not changing) result within the loop itself
for ($i = 0, $size = sizeof($post_data); $i < $size; $i++)
{
        do_something();
}

 

Use of in_array():
Try to avoid using in_array() on huge arrays, and try to not place them into loops if the array to check consist of more than 20 entries. in_array() can be very time consuming and uses a lot of cpu processing time. For little checks it is not noticable, but if checked against a huge array within a loop those checks alone can be a bunch of seconds. If you need this functionality, try using isset() on the arrays keys instead, actually shifting the values into keys and vice versa. A call to isset($array[$var]) is a lot faster than in_array($var, array_keys($array)) for example.

 

#3. Javascript guidelines

#3.1. General rules

  • Use JSDoc for classes, member variables, and methods 
  • Use single line ("//") comments everywhere else. 
  • Put a space after the "//" before the comment text. 
  • Use an  mpty line between descriptions and @param/@return/@throws declarations. 
  • Use @param, @return, @throws in that order.

#3.2. Naming

Naming should be as descriptive as possible. The only exception is the indexing variable in an loop. That can be shortened to a single letter starting from i.

  • variableNamesLikeThis 
  • functionNamesLikeThis 
  • ClassNamesLikeThis 
  • methodNamesLikeThis 
  • ConstantsLikeThis 

Private properties and methods of objects begin with an underscore _.

#3.3. Strings

Strings are written using single quotes or double quotes:

Good:

var  lyrics  =  'Never gonna Give you up, Never gonna Let you down' ;
var  lyrics  =  "Never gonna Give you up, Never gonna Let you down" ;

#3.4. Semicolon

Semicolon are always placed.

#3.5. Blocks

The opening brackets should always follow a space and not start at a new line

#3.6. The equality operator

Always use strict equality === (inequality !== ).

#3.7. Ternary operator

Always use spaces around the colon and question mark.

#3.8. eval

Avoid using eval. To parse json using JSON.parse.

#3.9. undefined

Check the value through a strict comparison.

 

 

#4. Using resources

Some times we need to attach some resources beside code — graphic, CSS and other type files. First of all while doing this take in mind it's sizes. We try to maintain Cotonti package reasonably lightweight. 

#4.1. Graphic files compression

For all graphic files we allow png/jpg/gif formats. More over it's a good practice to use special tools for addition (lossless) compression of graphic files (look for imageOptim, PNGOptimizer, ImageCatalyst, tinyPNG). 

#4.2. JS and CSS files compression

If you include or use in your package any packed or minimised resources (like JS and CSS files) be respectful to alse inclide source of it (so other developers can make further development). While using compressed versions of third party libraries and code  (like jQuery plugins, any CSS frameworks and so on) you should include links to official site or GitHub repo of this code to compressed files as comment.

If you bundle minimized version of your files (especially JS files) please insert a source mapping files for that (*.map). Many of modern compilers (Closure Compiler, JSMin, Uglifyjs2) can make a source maps. Example of command-line for Closure Compiler:

java -jar compiler.jar --js file_name.js  --create_source_map file_name.js.map --source_map_format=V3 --js_output_file file_name.min.!

 

#5. Helpful links and tools

Cotonti Development tools — helpful info about tools to maintain Cotonti CMF Coding Style and speed up development

Changelog files rules — useful how-to maintain CHANGELOG files


1. Joy  15. April 2009, 05:27
Thanks for the Info!
2. Sain  17. Dezember 2009, 03:59
Thank you. Now, will try to write some plugins.
Nur registrierte Benutzer können Kommentare schreiben