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);
» Double quotes are sometimes needed to not overcrowd the line with concatenations
$post_url = "posting." . PHP_EXT . "?mode=$mode&start=$start";
» Single quotes will speed up the parsing, even if sometimes many concatenations are needed, but you are sure that the vars are always included correctly
$post_url = IP_ROOT_PATH . 'posting.' . PHP_EXT . '?mode=' . $mode . '&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 tryed 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'];
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.
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);
» Right place to use them
$min = ($i < $j) ? $i : $j;
Don't use uninitialized variables.
For Icy Phoenix, we intend to use 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, examples:
» Wrong
» Right
» Also possible
if (isset($forum) && $forum == 5)
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.
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;
}
» Also good, if you have more code between the case and the break
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.
If no break is intended, please add a comment instead.
» Example with no break
switch ($mode)
{
case 'mode1':
// I am doing something here
// no break here
case 'mode2':
// I am doing something completely different here
break;
default:
// Always assume that the case got not catched
break;
}