Best practices
Вернуться к: Стандарты кодирования PEAR
There are other things not covered by PEAR Coding Standards which are mostly subject of personal preference and not directly related to readability of the code. Things like "single quotes vs double quotes" are features of PHP itself to make programming easier and there are no reasons not use one way in preference to another. Such best practices are left solely on developer to decide. The only recommendation could be made to keep consistency within package and respect personal style of other developers.
Readability of code blocks
Related lines of code should be grouped into blocks, seperated from each other to keep readability as high as possible. The definition of "related" depends on the code :)
For example:
<?php
if ($foo) {
$bar = 1;
}
if ($spam) {
$ham = 1;
}
if ($pinky) {
$brain = 1;
}
?>
is a lot easier to read when seperated:
<?php
if ($foo) {
$bar = 1;
}
if ($spam) {
$ham = 1;
}
if ($pinky) {
$brain = 1;
}
?>
Return early
To keep readability in functions and methods, it is wise to return early if simple conditions apply that can be checked at the beginning of a method:
<?php
function foo($bar, $baz)
{
if ($foo) {
//assume
//that
//here
//is
//the
//whole
//logic
//of
//this
//method
return $calculated_value;
} else {
return null;
}
}
?>
It's better to return early, keeping indentation and brain power needed to follow the code low.
<?php
function foo($bar, $baz)
{
if (!$foo) {
return null;
}
//assume
//that
//here
//is
//the
//whole
//logic
//of
//this
//method
return $calculated_value;
}
?>
Вернуться к: Стандарты кодирования PEAR