Log in | Back to darenet.org

Web Development

m (PHP Tags)
m (Code Complexity)
 
(34 intermediate revisions not shown)
Line 1: Line 1:
-
Here we'll attempt to explain the process we'll be using to develop the next generation of the DareNET web site. We will rely heavily on community interaction, whether through the forums or on IRC (#dev). IRC is perhaps the best place to find members of the development team and discuss ideas, latest code and make general comments.
+
{{Header|1 = <h2>'''[[Development Team|DareNET Development Wiki]]''' - {{FULLPAGENAME}}</h2>}}
 +
This document contains practices and guidelines which apply across languages. Contributors should follow these guidelines. These guidelines are not hard-and-fast but should be followed unless there is a compelling reason to deviate from them.
-
We'll maintain 3 version of the site.
+
==Code Complexity==
 +
* Prefer to write simple code which is easy to understand. The simplest code is not necessarily the smallest, and some changes which make code larger (such as decomposing complex expressions and choosing more descriptive names) may also make it simpler.
 +
* Be willing to make size tradeoffs in favor of simplicity.
 +
* Prefer simple methods and functions which take a small number of parameters. Avoid methods and functions which are long and complex, or take an innumerable host of parameters. When possible, decompose monolithic, complex methods into several focused, simpler ones.
-
* '''stable''' - for production (the version used on the main site) where stability is more important than features.
+
Avoid putting many ideas on a single line of code.
-
* '''trunk''' - development version where features are important and stability is necessary.
+
-
* '''branches''' - for testing, and development members interested in the most advanced feature set and willing to refine them some.
+
-
== Coding Standards ==
+
For example, avoid this kind of code:
-
=== Adding New Features ===
+
<pre>$category_map = array_combine(
 +
  $dates,
 +
  array_map(create_function('$z', 'return date("F Y", $z);'), $dates));</pre>
-
No new features should be added to stable or trunk, without having their own tests - which should be passed before committing them to the repository.
+
Expressing this complex transformation more simply produces more readable code:
-
=== Indentation ===
+
<php>$category_map = array();
-
One tab will be used for indentation.
+
foreach ($dates as $date) {
 +
  $category_map[$date] = date('F Y', $date);
 +
}</php>
-
So, indentation should look like this:
+
And, obviously, don't do this sort of thing:
-
<source lang="php" line start=1 >
+
<pre>if ($val = $some->complicatedConstruct() && !!~blarg_blarg_blarg() & $flags
-
<?php
+
      ? HOPE_YOU_MEMORIZED == $all_the_lexical_binding_powers : <<<'Q'
-
// base level
+
${hahaha}
-
    // level 1
+
Q
-
        // level 2
+
);</pre>
-
    // level 1
+
-
// base level
+
-
?>
+
-
</source>
+
-
Or:
+
==Performance==
 +
* Prefer to write efficient code.
 +
* Strongly prefer to drive optimization decisions with hard data. Avoid optimizing based on intuition or rumor if you can not support it with concrete measurements.
 +
* Prefer to optimize code which is slow and runs often. Optimizing code which is fast and runs rarely is usually a waste of time, and can even be harmful if it makes that code more difficult to understand or maintain. You can determine if code is fast or slow by measuring it.
 +
* Reject performance discussions that aren't rooted in concrete data.
-
<source lang="php" line start=1 >
+
==Naming Things==
-
$booleanVariable = true;
+
* Follow language-specific conventions.
-
$stringVariable = "moose";
+
* Name things unambiguously.
-
if ($booleanVariable) {
+
* Choose descriptive names.
-
echo "Boolean value is true";
+
* Avoid nonstandard abbreviations (common abbreviations like ID, URI and HTTP are fine).
-
if ($stringVariable == "moose") {
+
* Spell words correctly.
-
echo "We have encountered a moose";
+
* Use correct grammar.
-
}
+
-
}</source>
+
-
===Function Calls===
+
For example, avoid these sorts of naming choices:
-
Functions should be called without space between function's name and starting bracket. There should be one space between every parameter of a function call.
+
 +
<pre>$PIE->GET_FLAVOR();      //  Unconventional.
 +
$thing->doStuff();        //  Ambiguous.
 +
$list->empty();          //  Ambiguous -- is it isEmpty() or makeEmpty()?
 +
$e = 3;                  //  Not descriptive.
 +
$this->updtHndlr();      //  Nonstandard abbreviation.
 +
$this->chackSpulls();    //  Misspelling, ungrammatical.</pre>
-
<source lang="php" line start=1 ><?php
+
Prefer these:
-
$var = foo($bar, $bar2, $bar3);
+
-
?></source>
+
-
As you can see above there should be one space on both sides of equals sign (=). To increase the readability of the code you can add spaces (or tabs) before the equals sign, but only in the case of a multiple function call presented below:
+
<php>$pie->getFlavor();        //  Conventional.
 +
$pie->bake();            //  Unambiguous.
 +
$list->isEmpty();        //  Unambiguous.
 +
$list->makeEmpty();      //  Unambiguous.
 +
$edge_count = 3;          //  Descriptive.
 +
$this->updateHandler();  //  No nonstandard abbreviations.
 +
$this->getID();          //  Standard abbreviation.
 +
$this->checkSpelling();  //  Correct spelling and grammar.</php>
 +
==Error Handling==
 +
* Strongly prefer to detect errors.
 +
* Strongly prefer to fail fast and loudly. The maximum cost of script termination is known, bounded, and fairly small. The maximum cost of continuing script execution when errors have occurred is unknown and unbounded. This also makes APIs much easier to use and problems far easier to debug.
-
<source lang="php" line start=1 ><?php
+
When you ignore errors, defer error handling, or degrade the severity of errors by treating them as warnings and then dismissing them, you risk dangerous behavior which may be difficult to troubleshoot:
-
$varShort = foo($bar1);
+
-
$variableLong = foo($bar1);
+
-
?></source>
+
-
=== Commenting Code ===
+
<pre>exec('echo '.$data.' > file.bak');                //  Bad!
 +
do_something_dangerous();
-
All comments should be written in English, and should in a clear way describe the commented block of code.
+
exec('echo '.$data.' > file.bak', $out, $err);    //  Also bad!
 +
if ($err) {
 +
  debug_rlog("Unable to copy file!");
 +
}
 +
do_something_dangerous();</pre>
-
Comments can include the following phpDocumentor tags:  
+
Instead, fail loudly:
-
* [http://manual.phpdoc.org/HTMLframesConverter/phpdoc.de/phpDocumentor/tutorial_tags.access.pkg.html @access]
+
<php>exec('echo '.$data.' > file.bak', $out, $err);    // Better
-
* [http://manual.phpdoc.org/HTMLframesConverter/phpdoc.de/phpDocumentor/tutorial_tags.author.pkg.html @author]
+
if ($err) {
-
* [http://manual.phpdoc.org/HTMLframesConverter/phpdoc.de/phpDocumentor/tutorial_tags.copyright.pkg.html @copyright]
+
  throw new Exception("Unable to copy file!");
-
* [http://manual.phpdoc.org/HTMLframesConverter/phpdoc.de/phpDocumentor/tutorial_tags.deprecated.pkg.html @deprecated]
+
}
-
* [http://manual.phpdoc.org/HTMLframesConverter/phpdoc.de/phpDocumentor/tutorial_tags.example.pkg.html @example]
+
do_something_dangerous();</php>
-
* [http://manual.phpdoc.org/HTMLframesConverter/phpdoc.de/phpDocumentor/tutorial_tags.ignore.pkg.html @ignore]
+
-
* [http://manual.phpdoc.org/HTMLframesConverter/phpdoc.de/phpDocumentor/tutorial_tags.internal.pkg.html @internal]
+
-
* [http://manual.phpdoc.org/HTMLframesConverter/phpdoc.de/phpDocumentor/tutorial_tags.link.pkg.html @link]
+
-
* [http://manual.phpdoc.org/HTMLframesConverter/phpdoc.de/phpDocumentor/tutorial_tags.see.pkg.html @see]
+
-
* [http://manual.phpdoc.org/HTMLframesConverter/phpdoc.de/phpDocumentor/tutorial_tags.since.pkg.html @since]
+
-
* [http://manual.phpdoc.org/HTMLframesConverter/phpdoc.de/phpDocumentor/tutorial_tags.tutorial.pkg.html @tutorial]
+
-
* [http://manual.phpdoc.org/HTMLframesConverter/phpdoc.de/phpDocumentor/tutorial_tags.version.pkg.html @version]
+
-
* [http://manual.phpdoc.org/HTMLframesConverter/phpdoc.de/phpDocumentor/tutorial_tags.inlineinternal.pkg.html inline {@internal}}]
+
-
* [http://manual.phpdoc.org/HTMLframesConverter/phpdoc.de/phpDocumentor/tutorial_tags.inlineinheritdoc.pkg.html inline {@inheritdoc}}]
+
-
* [http://manual.phpdoc.org/HTMLframesConverter/phpdoc.de/phpDocumentor/tutorial_tags.inlinelink.pkg.html inline {@link}}]
+
-
PhpDoc tags are very much like JavaDoc tags in Java. Tags are only processed if they are the first thing in a DocBlock line, for example:
+
But the best approach is to use or write an API which simplifies condition handling and makes it easier to get right than wrong:
-
<source lang="php" line start=1 >
+
-
<?php
+
-
/**
+
-
* Tag example.
+
-
* @author this tag is parsed, but this @version is ignored
+
-
* @version 1.0 this tag is also parsed
+
-
*/
+
-
?></source>
+
-
There are 3 inline tags ({@internal}}, {@inheritdoc}} and {@link}}).
+
<php>execx('echo %s > file.bak', $data);              // Good
-
<source lang="php" line start=1 >
+
do_something_dangerous();
-
<?php
+
-
/**
+
-
* Example of inline phpDoc tags.
+
-
*
+
-
* This function works hard with {@link foo()} to rule the world.
+
-
  */
+
-
function bar() {
+
-
}
+
-
function foo() {
+
-
}
+
-
?></source>
+
-
=== Including Files ===
+
Filesystem::writeFile('file.bak', $data);        //  Best
 +
do_something_dangerous();</php>
-
When including files with classes or libraries, use only and always the [http://php.net/require_once require_once] function.
+
==Documentation, Comments and Formatting==
 +
* Prefer to remove code by deleting it over removing it by commenting it out. It shall live forever in source control, and can be retrieved therefrom if it is ever again called upon.
 +
* In source code, use only ASCII printable characters plus space and linefeed. Do not use UTF-8 or other multibyte encodings.
-
=== PHP Tags ===
+
== See Also ==
-
Always use long tags (<?php ?>) Instead of short tags (<? ?>).
+
* [[Web Development/PHP Coding Standards|PHP Coding Standards]]
 +
* [[Web Development/Javascript Coding Standards|Javascript Coding Standards]]

Current revision as of 19:10, 28 July 2011

In This Guide:

DareNET Development Wiki - Web Development

This document contains practices and guidelines which apply across languages. Contributors should follow these guidelines. These guidelines are not hard-and-fast but should be followed unless there is a compelling reason to deviate from them.

Code Complexity

  • Prefer to write simple code which is easy to understand. The simplest code is not necessarily the smallest, and some changes which make code larger (such as decomposing complex expressions and choosing more descriptive names) may also make it simpler.
  • Be willing to make size tradeoffs in favor of simplicity.
  • Prefer simple methods and functions which take a small number of parameters. Avoid methods and functions which are long and complex, or take an innumerable host of parameters. When possible, decompose monolithic, complex methods into several focused, simpler ones.

Avoid putting many ideas on a single line of code.

For example, avoid this kind of code:

$category_map = array_combine(
  $dates,
  array_map(create_function('$z', 'return date("F Y", $z);'), $dates));

Expressing this complex transformation more simply produces more readable code:

$category_map = array();
foreach ($dates as $date) {
  $category_map[$date] = date('F Y', $date);
}

And, obviously, don't do this sort of thing:

if ($val = $some->complicatedConstruct() && !!~blarg_blarg_blarg() & $flags
      ? HOPE_YOU_MEMORIZED == $all_the_lexical_binding_powers : <<<'Q'
${hahaha}
Q
);

Performance

  • Prefer to write efficient code.
  • Strongly prefer to drive optimization decisions with hard data. Avoid optimizing based on intuition or rumor if you can not support it with concrete measurements.
  • Prefer to optimize code which is slow and runs often. Optimizing code which is fast and runs rarely is usually a waste of time, and can even be harmful if it makes that code more difficult to understand or maintain. You can determine if code is fast or slow by measuring it.
  • Reject performance discussions that aren't rooted in concrete data.

Naming Things

  • Follow language-specific conventions.
  • Name things unambiguously.
  • Choose descriptive names.
  • Avoid nonstandard abbreviations (common abbreviations like ID, URI and HTTP are fine).
  • Spell words correctly.
  • Use correct grammar.

For example, avoid these sorts of naming choices:

$PIE->GET_FLAVOR();       //  Unconventional.
$thing->doStuff();        //  Ambiguous.
$list->empty();           //  Ambiguous -- is it isEmpty() or makeEmpty()?
$e = 3;                   //  Not descriptive.
$this->updtHndlr();       //  Nonstandard abbreviation.
$this->chackSpulls();     //  Misspelling, ungrammatical.

Prefer these:

$pie->getFlavor();        //  Conventional.
$pie->bake();             //  Unambiguous.
$list->isEmpty();         //  Unambiguous.
$list->makeEmpty();       //  Unambiguous.
$edge_count = 3;          //  Descriptive.
$this->updateHandler();   //  No nonstandard abbreviations.
$this->getID();           //  Standard abbreviation.
$this->checkSpelling();   //  Correct spelling and grammar.

Error Handling

  • Strongly prefer to detect errors.
  • Strongly prefer to fail fast and loudly. The maximum cost of script termination is known, bounded, and fairly small. The maximum cost of continuing script execution when errors have occurred is unknown and unbounded. This also makes APIs much easier to use and problems far easier to debug.

When you ignore errors, defer error handling, or degrade the severity of errors by treating them as warnings and then dismissing them, you risk dangerous behavior which may be difficult to troubleshoot:

exec('echo '.$data.' > file.bak');                //  Bad!
do_something_dangerous();

exec('echo '.$data.' > file.bak', $out, $err);    //  Also bad!
if ($err) {
  debug_rlog("Unable to copy file!");
}
do_something_dangerous();

Instead, fail loudly:

exec('echo '.$data.' > file.bak', $out, $err);    //  Better
if ($err) {
  throw new Exception("Unable to copy file!");
}
do_something_dangerous();

But the best approach is to use or write an API which simplifies condition handling and makes it easier to get right than wrong:

execx('echo %s > file.bak', $data);               //  Good
do_something_dangerous();
 
Filesystem::writeFile('file.bak', $data);         //  Best
do_something_dangerous();

Documentation, Comments and Formatting

  • Prefer to remove code by deleting it over removing it by commenting it out. It shall live forever in source control, and can be retrieved therefrom if it is ever again called upon.
  • In source code, use only ASCII printable characters plus space and linefeed. Do not use UTF-8 or other multibyte encodings.

See Also