Note:

If you want to create a new page for developers, you should create it on the Moodle Developer Resource site.

Coding style: Difference between revisions

From MoodleDocs
No edit summary
Line 161: Line 161:
Use lower case for '''true''', '''false''' and '''null'''.
Use lower case for '''true''', '''false''' and '''null'''.


==Coding Style==
 
===Strings===
==Strings==


Since string performance is not an issue in current versions of PHP, the main criteria for strings is readability.  
Since string performance is not an issue in current versions of PHP, the main criteria for strings is readability.  




====Single quotes====
===Single quotes===


Always use single quotes when a string is literal, or contains a lot of double quotes (like HTML):
Always use single quotes when a string is literal, or contains a lot of double quotes (like HTML):
Line 177: Line 177:
</code>
</code>


====Double quotes====
===Double quotes===


These are a lot less useful in Moodle.   
These are a lot less useful in Moodle.   
Line 188: Line 188:
</code>
</code>


====Variable substitution====
===Variable substitution===


Variable substitution can use either of these forms:
Variable substitution can use either of these forms:
Line 198: Line 198:
</code>
</code>


====String concatenation====
===String concatenation===


Strings must be concatenated using the "." operator.
Strings must be concatenated using the "." operator.
Line 214: Line 214:
</code>
</code>


===Arrays===
==Arrays==


====Numerically indexed arrays====
===Numerically indexed arrays===


Negative numbers are not permitted as indices.
Negative numbers are not permitted as indices.
Line 237: Line 237:




====Associative arrays====
===Associative arrays===


Use multiple lines where possible, and pad the successive lines with spaces like this:
Use multiple lines where possible, and pad the successive lines with spaces like this:
Line 246: Line 246:
</code>
</code>


===Classes===
==Classes==


====Class declarations====
===Class declarations===


Classes must be named according to Moodle's naming conventions.
Classes must be named according to Moodle's naming conventions.
Line 274: Line 274:
</code>  
</code>  


====Class member variables====
===Class member variables===


Member variables must be named according to Moodle's variable naming conventions.
Member variables must be named according to Moodle's variable naming conventions.
Line 282: Line 282:
The var construct is not permitted. Member variables always declare their visibility by using one of the '''private''', '''protected''', or '''public''' modifiers. Giving access to member variables directly by declaring them as public is permitted but discouraged in favor of accessor methods (set/get).
The var construct is not permitted. Member variables always declare their visibility by using one of the '''private''', '''protected''', or '''public''' modifiers. Giving access to member variables directly by declaring them as public is permitted but discouraged in favor of accessor methods (set/get).


===Functions and methods===
==Functions and methods==
====Function and method declaration====
===Function and method declaration===


Functions must be named according to the Moodle function naming conventions.
Functions must be named according to the Moodle function naming conventions.
Line 315: Line 315:




====Function and method usage====
===Function and method usage===


Function arguments should be separated by a single trailing space after the comma delimiter.  
Function arguments should be separated by a single trailing space after the comma delimiter.  
Line 323: Line 323:
</code>
</code>


===Control statements===
==Control statements==


In general, use white space liberally between lines and so on, to add clarity.
In general, use white space liberally between lines and so on, to add clarity.




====If / else====
===If / else===


Put a space before and after the control statement in brackets, and separate the operators by spaces within the brackets.  Use inner brackets to improve logical grouping if it helps.  
Put a space before and after the control statement in brackets, and separate the operators by spaces within the brackets.  Use inner brackets to improve logical grouping if it helps.  
Line 348: Line 348:
</code>
</code>


====Switch====
===Switch===


Put a space before and after the control statement in brackets, and separate the operators by spaces within the brackets.  Use inner brackets to improve logical grouping if it helps.  
Put a space before and after the control statement in brackets, and separate the operators by spaces within the brackets.  Use inner brackets to improve logical grouping if it helps.  
Line 368: Line 368:




====Foreach====
===Foreach===


As above, uses spaces like this:
As above, uses spaces like this:
Line 378: Line 378:
</code>
</code>


===Inline documentation===
==Inline documentation==
====Documentation format====
===Documentation format===


Comments should be added as much as is practical, to explain the code flow and the purpose of functions and variables.
Comments should be added as much as is practical, to explain the code flow and the purpose of functions and variables.
Line 407: Line 407:
</code>
</code>


====Files====
===Files===
====Classes====
===Classes===
====Functions====
===Functions===
====Require / include====
===Require / include===


==Errors and Exceptions==
==Errors and Exceptions==
====Exception best practices====
====Exception best practices====

Revision as of 03:19, 30 April 2009

This new version of the Moodle code style guidelines is based on the Zend guidelines and our old Coding page.

It's still draft, come back in a day or two :)

Overview

Scope

This document describes style guidelines for developers working on or with Moodle code.

it is just one part of the overall coding guidelines.

Goals

Consistent coding style is important in any development project, and particularly when many developers are involved. A standard style helps to ensure that the code is easier to read and understand, which helps overall quality.

Abstract goals we strive for:

  • simplicity
  • readability
  • tool friendliness, such as use of method signatures, constants, and patterns that support IDE tools and auto-completion of method, class, and constant names.

When considering the goals above, each situation requires an examination of the circumstances and balancing of various trade-offs.

Note that much of the existing Moodle code may not follow all of these guidelines - we continue to upgrade this code when we see it.

File Formatting

PHP tags

Always use "long" php tags. However, to avoid whitespace problems, DO NOT include the closing tag at the very end of the file.

<?php

   include('config.php');

Indentation

Use an indent of 4 spaces with no tab characters. Editors should be configured to treat tabs as spaces in order to prevent injection of new tab characters into the source code.

Don't indent the main script level:

GOOD: <?php // $Id$ $a = required_param('a', PARAM_INT); if ($a > 10) {

   call_some_error($a);

} else {

   do_something_with($a);

} ?>

BAD: <?php // $Id$

   $a = required_param('a', PARAM_INT);
   if ($a > 10) {
       call_some_error($a);
   } else {
       do_something_with($a);
   }

?>

Maximum Line Length

Aim for 80 characters if it is convenient.

However, you can go up to 120 characters if it helps overall readability.

Line Termination

Use standard Unix text format. Lines must end only with a linefeed (LF). Linefeeds are represented as ordinal 10, or hexadecimal 0x0A.

Do not use carriage returns (CR) like Macintosh computers (0x0D).

Do not use the carriage return/linefeed combination (CRLF) as Windows computers (0x0D, 0x0A).

Lines should not contain trailing spaces. In order to facilitate this convention, most editors can be configured to strip trailing spaces, such as upon a save operation.

Naming Conventions

Filenames

Filenames should :

  • be whole english words
  • be as short as possible
  • use lowercase letters only
  • end in .php, .html, .js, or .xml

Classes

Class names should always be lowercase english words, separated by underscores:

class some_custom_class {

   function class_method() {
       echo "foo";
   }

}

Functions and Methods

Function names should be simple English lowercase words, and start with the name of the module to avoid conflicts between modules. Words should be separated by underscores.

Verbosity is encouraged: function names should be as illustrative as is practical to enhance understanding.

Note there is no space between the function name and the following (brackets).

function forum_set_display_mode($mode = 0) {

   global $USER, $CFG;
        
   if ($mode) {
       $USER->mode = $mode;
   } else if (empty($USER->mode)) {
       $USER->mode = $CFG->forum_displaymode;
   }

}

Function Parameters

Parameters are always simple lowercase English words (sometimes more than one, like $initialvalue), and should always have sensible defaults if possible.

Use "null" as the default value instead of "false" for situations like this where a default value isn't needed. public function foo($required, $optional = null)

However, if an optional parameter is boolean, and its logical default value should be true, or false, then using true or false is acceptable.

Variables

Variable names should always be easy-to-read, meaningful lower-case English words. If you really need more than one word then run them together, but keep them short as possible. Use plural names for arrays of objects.

    GOOD: $quiz
    GOOD: $errorstring
    GOOD: $assignments (for an array of objects)
    GOOD: $i (but only in little loops)
    BAD: $Quiz
    BAD: $camelCase
    BAD: $aReallyLongVariableNameWithoutAGoodReason
    BAD: $error_string

Constants

Constants should always be in upper case, and always start with the name of the module. They should have words separated by underscores. define("FORUM_MODE_FLATOLDEST", 1);

Booleans and the NULL Value

Use lower case for true, false and null.


Strings

Since string performance is not an issue in current versions of PHP, the main criteria for strings is readability.


Single quotes

Always use single quotes when a string is literal, or contains a lot of double quotes (like HTML):

$a = 'Example String'; echo ''; $html = '<a href="http://something" title="something">Link</a>';

Double quotes

These are a lot less useful in Moodle.

Use double quotes when you need to include plain variables or a lot of single quotes. In Moodle 2.0 or later you won't need to be doing a lot of single quotes for SQL so that's not an issue.

echo "$string"; $statement = "You aren't serious!";

Variable substitution

Variable substitution can use either of these forms:

$greeting = "Hello $name, welcome back!";

$greeting = "Hello {$name}, welcome back!";

String concatenation

Strings must be concatenated using the "." operator.

$longstring = $several.$short.'strings';

If the lines are long, break the statement into multiple lines to improve readability. In these cases, put the "dot" at the end of each line.

$sql = "SELECT `id`, `username` FROM `user` ".

      "WHERE `username` = 'susan' ".
      "ORDER BY `id` ASC ";

Arrays

Numerically indexed arrays

Negative numbers are not permitted as indices.

An indexed array may start with any non-negative number, however all base indices besides 0 are discouraged.

When declaring indexed arrays with the array function, a trailing space must be added after each comma delimiter to improve readability:

$myarray = array(1, 2, 3, 'Stuff', 'Here');

Multi-line indexed arrays are fine, but pad each successive line with spaces so that the beginning of each line is aligned:

$myarray = array(1, 2, 3, 'Stuff', 'Here',

                $a, $b, $c,
                56.44, $d, 500);


Associative arrays

Use multiple lines where possible, and pad the successive lines with spaces like this:

$myarray = array('firstkey' => 'firstvalue',

                'secondkey' => 'secondvalue');

Classes

Class declarations

Classes must be named according to Moodle's naming conventions.

The brace should always be written on the line beside the class name.

Every class must have a documentation block that conforms to the PHPDocumentor standard.

All code in a class must be indented with four spaces.

Only one class is permitted in each PHP file.

Placing additional code in class files is permitted but discouraged. In such files, two blank lines must separate the class from any additional PHP code in the class file.

An example:

/**

* Documentation Block Here
*/

class SampleClass {

   // all contents of class
   // must be indented four spaces

}

Class member variables

Member variables must be named according to Moodle's variable naming conventions.

Any variables declared in a class must be listed at the top of the class, above the declaration of any methods.

The var construct is not permitted. Member variables always declare their visibility by using one of the private, protected, or public modifiers. Giving access to member variables directly by declaring them as public is permitted but discouraged in favor of accessor methods (set/get).

Functions and methods

Function and method declaration

Functions must be named according to the Moodle function naming conventions.

Methods inside classes must always declare their visibility by using one of the private, protected, or public modifiers.

As with classes, the brace should always be written on same line as the function name.

Don't leave spaces between the function name and the opening parenthesis for the arguments.

Functions in the global scope are strongly discouraged.

The return value must not be enclosed in parentheses. This can hinder readability, in additional to breaking code if a method is later changed to return by reference.

/**

* Documentation Block Here
*/

class sample_class {

   /**
    * Documentation Block Here
    */
   public function sample_function () {
       // all contents of function
       // must be indented four spaces
       return true;
   }

}


Function and method usage

Function arguments should be separated by a single trailing space after the comma delimiter.

threeArguments(1, 2, 3);

Control statements

In general, use white space liberally between lines and so on, to add clarity.


If / else

Put a space before and after the control statement in brackets, and separate the operators by spaces within the brackets. Use inner brackets to improve logical grouping if it helps.

Indent with four spaces.

Don't use elseif !

Always use braces (even if the block is one line and PHP doesn't require it).

if ($x == $y) {

   $a = $b;

} else if ($x == $z) {

   $a = $c;

} else {

   $a = $d;

}

Switch

Put a space before and after the control statement in brackets, and separate the operators by spaces within the brackets. Use inner brackets to improve logical grouping if it helps.

Always indent with four spaces. Content under each case statement should be indented a further four spaces.

switch ($something) {

   case 1:
       break;
   case 2:
       break;
   default:
       break;

}


Foreach

As above, uses spaces like this:

foreach ($objects as $key => $thing) {

   process($thing);

}

Inline documentation

Documentation format

Comments should be added as much as is practical, to explain the code flow and the purpose of functions and variables.

  • Every function (and class) should use phpDoc format. This allows code documentation to be generated automatically.
  • Inline comments should use the // style, laid out neatly so that it fits among the code and lines up with it.

/**

* The description should be first, with asterisks laid out exactly
* like this example. If you want to refer to a another function,
* do it like this: {@link clean_param()}. Then, add descriptions
* for each parameter as follows.
*
* @param int $postid The PHP type is followed by the variable name
* @param array $scale The PHP type is followed by the variable name
* @param array $ratings The PHP type is followed by the variable name
* @return mixed
  • /

function forum_get_ratings_mean($postid, $scale, $ratings=NULL) {

    if (!$ratings) {
        $ratings = array();     // Initialize the empty array
        if ($rates = get_records("forum_ratings", "post", $postid)) {
            // Process each rating in turn
            foreach ($rates as $rate) {
     ... etc.

Files

Classes

Functions

Require / include

Errors and Exceptions

Exception best practices