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
Line 188: Line 188:


===Arrays===
===Arrays===
====Numerically indexed 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:
<code php>
$myarray = array(1, 2, 3, 'Stuff', 'Here');
</code>
Multi-line indexed arrays are fine, but pad each successive line with spaces so that the beginning of each line is aligned:
<code php>
$myarray = array(1, 2, 3, 'Stuff', 'Here',
                $a, $b, $c,
                56.44, $d, 500);
</code>
====Associative arrays====
====Associative arrays====
Use multiple lines where possible, and pad the successive lines with spaces like this:
$myarray = array('firstkey'  => 'firstvalue',
                'secondkey' => 'secondvalue');
===Classes===
===Classes===
====Class declarations====
====Class declarations====

Revision as of 14:50, 29 April 2009


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


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.

Maximum Line Length

Aim for 80 characters if it is convenient. However, you can go longer if it helps overall readability. The maximum line length is 120 characters.

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: $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.

Coding Style

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

Class member variables

Functions and methods

Function and method declaration

Function and method usage

Control statements

If / else

Switch

Inline documentation

Documentation format

Files

Classes

Functions

Require / include

Errors and Exceptions

Exception best practices