Jump to content

Manual:Coding conventions: Difference between revisions

From mediawiki.org
Content deleted Content added
PHP pitfalls: +my mailing list post
spacing and link tweaks, removed stuff about preferring ef/eg in extension code over wf/wg per Tim's r70755
Line 1: Line 1:
This page describes the '''coding conventions''' used within the [[Manual:Code|MediaWiki codebase]] and extensions which are intended for use on Wikimedia websites, including appropriate naming conventions. If you would like a short checklist to help you review your commits, try using the [[Manual:Pre-Commit_Checklist|pre-commit checklist]].
This page describes the '''coding conventions''' used within the [[Manual:Code|MediaWiki codebase]] and extensions which are intended for use on Wikimedia websites, including appropriate naming conventions. If you would like a short checklist to help you review your commits, try using the [[Manual:Pre-commit checklist|pre-commit checklist]].


==Whitespace etc.==
==Whitespace etc.==

Lines should be indented with a single tab character per indenting level. You should make no assumptions about the number of spaces per tab. Most MediaWiki developers find 4 spaces per tab to be best for readability, but many systems are configured to use 8 spaces per tab.
Lines should be indented with a single tab character per indenting level. You should make no assumptions about the number of spaces per tab. Most MediaWiki developers find 4 spaces per tab to be best for readability, but many systems are configured to use 8 spaces per tab.


Line 12: Line 11:


===Indenting and alignment===
===Indenting and alignment===

MediaWiki's indenting style is similar to the so-called "[[w:Indent_style#Variant:_1TBS|One True Brace Style]]". Braces are placed on the same line as the start of the function, conditional, loop, etc.
MediaWiki's indenting style is similar to the so-called "[[w:Indent_style#Variant:_1TBS|One True Brace Style]]". Braces are placed on the same line as the start of the function, conditional, loop, etc.


Line 66: Line 64:


===Line continuation===
===Line continuation===

Lines should be broken at between 80 and 100 columns. There are some rare exceptions to this. Functions which take lots of parameters are not exceptions.
Lines should be broken at between 80 and 100 columns. There are some rare exceptions to this. Functions which take lots of parameters are not exceptions.


Line 105: Line 102:


===Spaces===
===Spaces===

MediaWiki favours a heavily-spaced style for optimum readability.
MediaWiki favours a heavily-spaced style for optimum readability.


Line 146: Line 142:


===Braceless control structures===
===Braceless control structures===

Single-line if statements are rarely used. They reduce the readability of the code by moving important statements away from the left margin, where the reader is looking for them.
Single-line if statements are rarely used. They reduce the readability of the code by moving important statements away from the left margin, where the reader is looking for them.


Line 176: Line 171:
This has the potential to create subtle bugs.
This has the potential to create subtle bugs.


=== emacs style ===
===emacs style===
In emacs, using <tt>php-mode.el</tt> from
In emacs, using <tt>php-mode.el</tt> from
[http://ourcomments.org/Emacs/nXhtml/doc/nxhtml.html nXHTML mode],
[http://ourcomments.org/Emacs/nXhtml/doc/nxhtml.html nXHTML mode],
Line 232: Line 227:


===Assignment expressions===
===Assignment expressions===

Using assignment as an expression is surprising to the reader and looks like an error. Do not write code like this:
Using assignment as an expression is surprising to the reader and looks like an error. Do not write code like this:


Line 253: Line 247:


<source lang="php">
<source lang="php">
$res = $dbr->query( 'SELECT * from some_table' );
$res = $dbr->query( 'SELECT * FROM some_table' );
while ( $row = $dbr->fetchObject( $res ) ) {
while ( $row = $dbr->fetchObject( $res ) ) {
showRow( $row );
showRow( $row );
Line 262: Line 256:


<source lang="php">
<source lang="php">
$res = $dbr->query( 'SELECT * from some_table' );
$res = $dbr->query( 'SELECT * FROM some_table' );
foreach ( $res as $row ) {
foreach ( $res as $row ) {
showRow( $row );
showRow( $row );
Line 269: Line 263:


===Ternary operator===
===Ternary operator===

The ternary operator can be used profitably if the expressions are very short and obvious:
The ternary operator can be used profitably if the expressions are very short and obvious:


Line 279: Line 272:


===String literals===
===String literals===

For simple string literals, single quotes are slightly faster for PHP to parse than double quotes. Perhaps more importantly, they are easier to type, since you don't have to press shift. For these reasons, single quotes are preferred in cases where they are equivalent to double quotes.
For simple string literals, single quotes are slightly faster for PHP to parse than double quotes. Perhaps more importantly, they are easier to type, since you don't have to press shift. For these reasons, single quotes are preferred in cases where they are equivalent to double quotes.


Line 319: Line 311:


===C borrowings===
===C borrowings===

The PHP language was designed by people who love C and wanted to bring souvenirs from that language into PHP. But PHP has some important differences from C.
The PHP language was designed by people who love C and wanted to bring souvenirs from that language into PHP. But PHP has some important differences from C.


Line 329: Line 320:


===PHP pitfalls===
===PHP pitfalls===

* Understand and read the documentation for <tt>[http://us.php.net/isset isset()]</tt> and <tt>[http://us.php.net/empty empty()]</tt>. Use them only when appropriate.
* Understand and read the documentation for <tt>[http://us.php.net/isset isset()]</tt> and <tt>[http://us.php.net/empty empty()]</tt>. Use them only when appropriate.
** <tt>empty()</tt> is inverted conversion to boolean with error suppression. Only use it when you really want to suppress errors. Otherwise just use <tt>!</tt>. Do not use it to test if an array is empty, unless you simultaneously want to check if the variable is unset.
** <tt>empty()</tt> is inverted conversion to boolean with error suppression. Only use it when you really want to suppress errors. Otherwise just use <tt>!</tt>. Do not use it to test if an array is empty, unless you simultaneously want to check if the variable is unset.
Line 343: Line 333:


==Classes==
==Classes==

As a holdover from PHP 4.x's lack of private class members and methods, older code will be marked with comments such as <tt>/** @private */</tt> to indicate the intention; respect this as if it were enforced by the compiler.
As a holdover from PHP 4.x's lack of private class members and methods, older code will be marked with comments such as <tt>/** @private */</tt> to indicate the intention; respect this as if it were enforced by the compiler.


Line 350: Line 339:
==Naming==
==Naming==


=== Files ===
===Files===

Files which contain include code should be named in <tt>UpperCamelCase</tt>. Name the file after the most important class it contains; most files will contain only one class, or a base class and a number of descendants. For instance, [[svn:trunk/phase3/includes/Title.php|Title.php]] contains only the <tt>Title</tt> class; [[svn:trunk/phase3/includes/HTMLForm.php|HTMLForm.php]] contains the base class <tt>HTMLForm</tt>, but also the related class <tt>HTMLFormField</tt> and its descendants.
Files which contain include code should be named in <tt>UpperCamelCase</tt>. Name the file after the most important class it contains; most files will contain only one class, or a base class and a number of descendants. For instance, [[svn:trunk/phase3/includes/Title.php|Title.php]] contains only the <tt>Title</tt> class; [[svn:trunk/phase3/includes/HTMLForm.php|HTMLForm.php]] contains the base class <tt>HTMLForm</tt>, but also the related class <tt>HTMLFormField</tt> and its descendants.


Line 358: Line 346:
Never include spaces in filenames or directories, or use non-ASCII characters. For lowercase titles, hyphens are preferred to underscores.
Never include spaces in filenames or directories, or use non-ASCII characters. For lowercase titles, hyphens are preferred to underscores.


=== Code elements ===
===Code elements===
Use [[w:CamelCase|lowerCamelCase]] when naming functions or variables. For example: <source lang="php">private function doSomething( $userPrefs, $editSummary )</source> Use UpperCamelCase when naming classes: <tt>class ImportantClass</tt>. Use uppercase with underscores for global and class constants: <tt>DB_MASTER</tt>, <tt>Revision::REV_DELETED_TEXT</tt>. Other variables are usually lowercase or lowerCamelCase; avoid using underscores in variable names.

Use [[w:CamelCase|lowerCamelCase]] when naming functions or variables. For example: <source lang="php">private function doSomething( $userPrefs, $editSummary )</source> Use UpperCamelCase when naming classes: <tt>class ImportantClass</tt>. Use uppercase with underscores for global and class constants: <tt>DB_WRITE</tt>, <tt>Revision::REV_DELETED_TEXT</tt>. Other variables are usually lowercase or lowerCamelCase; avoid using underscores in variable names.


There are also some prefixes used in different places:
There are also some prefixes used in different places:


====Functions====
====Functions====

* <tt>wf</tt> (wiki functions) - Top-level functions, e.g. <source lang="php">function wfFuncname() { ... }</source>
* <tt>wf</tt> (wiki functions) - Top-level functions, e.g. <source lang="php">function wfFuncname() { ... }</source>


Line 371: Line 357:


====Variables====
====Variables====
* <tt>wg</tt> - global variables, e.g. <tt>$wgVersion</tt>, <tt>$wgTitle</tt>. Always use this for new globals, so that it's easy to spot missing "global $wgFoo" declarations. In extensions, the extension name should be used as a namespace delimiter. For example, <tt>$wgAbuseFilterConditionLimit</tt>, '''not''' $wgConditionLimit.

* <tt>wg</tt> - global variables, e.g. <tt>$wgVersion</tt>, <tt>$wgTitle</tt>. Always use this for new globals, so that it's easy to spot missing "global $wgFoo" declarations.
* <tt>m</tt> - object member variables: <tt>$this->mPage</tt>. This is '''discouraged in new code''', but try to stay consistent within a class.
* <tt>m</tt> - object member variables: <tt>$this->mPage</tt>. This is '''discouraged in new code''', but try to stay consistent within a class.

====Extension Functions and Variables====
*<tt>ef</tt> - extension functions: top-level functions added by user extensions
*<tt>eg</tt> - extension globals.

You should include the Extension name as a namespace delimiter, whether or not you use the <tt>eg</tt> prefix: <tt>$wgAbuseFilterConditionLimit</tt>, <tt>$egCentralNoticeTables</tt>.


====HTTP and session stuff====
====HTTP and session stuff====

The following may be seen in old code but are discouraged in new code:
The following may be seen in old code but are discouraged in new code:


Line 436: Line 414:


==To do==
==To do==

* Naming
* Naming
* Function parameter choice
* Function parameter choice

Revision as of 10:29, 9 August 2010

This page describes the coding conventions used within the MediaWiki codebase and extensions which are intended for use on Wikimedia websites, including appropriate naming conventions. If you would like a short checklist to help you review your commits, try using the pre-commit checklist.

Whitespace etc.

Lines should be indented with a single tab character per indenting level. You should make no assumptions about the number of spaces per tab. Most MediaWiki developers find 4 spaces per tab to be best for readability, but many systems are configured to use 8 spaces per tab.

All text files should be checked in to Subversion with svn:eol-style set to "native". This is necessary to prevent corruption by certain Windows-based text editors.

All text files are encoded with UTF-8. Be sure that your editor supports this.

Do not use MS Notepad to edit files. Notepad inserts unicode byte order marks which stop PHP files from working.

Indenting and alignment

MediaWiki's indenting style is similar to the so-called "One True Brace Style". Braces are placed on the same line as the start of the function, conditional, loop, etc.

function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
	if ( is_null( $ts ) ) {
		return null;
	} else {
		return wfTimestamp( $outputtype, $ts );
	}
}

Multi-line statements are written with the second and subsequent lines being indented by one extra level:

return strtolower( $val ) == 'on'
	|| strtolower( $val ) == 'true'
	|| strtolower( $val ) == 'yes'
	|| preg_match( "/^\s*[+-]?0*[1-9]/", $val );

Use indenting and line breaks to clarify the logical structure of your code. Expressions which nest multiple levels of parentheses or similar structures may begin a new indenting level with each nesting level:

$wgAutopromote = array(
	'autoconfirmed' => array( '&',
		array( APCOND_EDITCOUNT, &$wgAutoConfirmCount ),
		array( APCOND_AGE, &$wgAutoConfirmAge ),
	),
);

Mid-line vertical alignment should be achieved with spaces. For instance this:

$namespaceNames = array(
	NS_MEDIA            => 'Media',
	NS_SPECIAL          => 'Special',
	NS_MAIN             => '',

Is achieved as follows with spaces rendered as dots:

$namespaceNames·=·array(
   →    NS_MEDIA············=>·'Media',
   →    NS_SPECIAL··········=>·'Special',
   →    NS_MAIN·············=>·'',

In general, you should avoid using vertical alignment, since it tends to create diffs which are hard to interpret, since the width allowed for the left column constantly has to be increased as more items are added.

Line continuation

Lines should be broken at between 80 and 100 columns. There are some rare exceptions to this. Functions which take lots of parameters are not exceptions.

The operator separating the two lines may be placed on either the following line or the preceding line. An operator placed on the following line is more visible and so is more often used when the author wants to draw attention to it:

return strtolower( $val ) == 'on'
	|| strtolower( $val ) == 'true'
	|| strtolower( $val ) == 'yes'
	|| preg_match( "/^\s*[+-]?0*[1-9]/", $val );

An operator placed on the preceding line is less visible, and is used for more common types of continuation such as concatenation and comma:

$wgOut->addHTML(
	Xml::fieldset(  wfMsg( 'importinterwiki' ) ) .
	Xml::openElement( 'form', array( 'method' => 'post', 'action' => $action, 'id' => 'mw-import-interwiki-form' ) ) .
	wfMsgExt( 'import-interwiki-text', array( 'parse' ) ) .
	Xml::hidden( 'action', 'submit' ) .
	Xml::hidden( 'source', 'interwiki' ) .
	Xml::hidden( 'editToken', $wgUser->editToken() ) .

When continuing "if" statements, a switch to Allman-style braces makes the separation between the condition and the body clear:

if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
    strlen( $dbkey ) > 512 )
{
	return false;
}

Opinions differ on the amount of indentation that should be used for the conditional part. Using an amount of indentation different to that used by the body makes it more clear that the conditional part is not the body, but this is not universally observed.

Continuation of conditionals and very long expressions tend to be ugly whichever way you do them. So it's sometimes best to break them up by means of temporary variables.

Spaces

MediaWiki favours a heavily-spaced style for optimum readability.

Put spaces on either side of binary operators, for example:

$a = $b + $c;

NOT

$a=$b+$c;

Put spaces next to parentheses on the inside, except where the parentheses are empty. Do not put a space following a function name.

$a = getFoo( $b );
$c = getBar();

Opinions differ as to whether control structures if, while, for and foreach should be followed by a space; the following two styles are acceptable:

// Spacey
if ( isFoo() ) {
	$a = 'foo';
}

// Not so spacey
if( isFoo() ) {
	$a = 'foo';
}

Single-line comments should have a space between the # or // and the comment text.

To help developers fix code with an inadequately spacey style, a tool called stylize.php has been created, which uses PHP's tokenizer extension to add spaces at the relevant places.

Braceless control structures

Single-line if statements are rarely used. They reduce the readability of the code by moving important statements away from the left margin, where the reader is looking for them.

Remember that making code shorter doesn't make it simpler. The goal of coding style is to communicate effectively with humans, not to fit computer-readable text into a small space.

Most MediaWiki developers favour fully-braced control structures:

if ( $done ) {
	return;
}

This avoids a common logic error, which is especially prevalent when the developer is using a text editor which does not have a "smart indenting" feature. The error occurs when a single-line block is later extended to two lines:

if ( $done )
	return;

Later changed to:

if ( $done )
	$this->cleanup();
	return;

This has the potential to create subtle bugs.

emacs style

In emacs, using php-mode.el from nXHTML mode, you can set up a MediaWiki minor mode in your .emacs file:

(defconst mw-style
  '((indent-tabs-mode . t)
    (tab-width . 4)
    (c-basic-offset . 4)
    (c-offsets-alist . ((case-label . +)
                        (arglist-cont-nonempty . +)
                        (arglist-close . 0)
                        (cpp-macro . (lambda(x) (cdr x)))
                        (comment-intro . 0)))
    (c-hanging-braces-alist
        (defun-open after)
        (block-open after)
        (defun-close))))

(c-add-style "MediaWiki" mw-style)

(define-minor-mode mw-mode
  "tweak style for mediawiki"
  nil " MW" nil
  (delete-trailing-whitespace)
  (tabify (point-min) (point-max))
  (c-subword-mode 1))

;; Add other sniffers as needed
(defun mah/sniff-php-style (filename)
  "Given a filename, provide a cons cell of
   (style-name . function)
where style-name is the style to use and function
sets the minor-mode"
  (cond ((string-match "/\\(mw[^/]*\\|mediawiki\\)/"
                       filename)
         (cons "MediaWiki" 'mah/mw-mode))
        (t
         (cons "cc-mode" (lambda (n) t)))))

(add-hook 'php-mode-hook (lambda () (let ((ans (when (buffer-file-name)
                                                 (mah/sniff-php-style (buffer-file-name)))))
                                      (c-set-style (car ans))
                                      (funcall (cdr ans) 1))))

The above mah/sniff-php-style function will check your path when php-mode is invoked to see if it contains “mw” or “mediawiki” and set the buffer to use the mw-mode minor mode for editing MediaWiki source. You will know that the buffer is using mw-mode because you'll see something like “PHP MW” or “PHP/lw MW” in the mode line.

Logical structure

Assignment expressions

Using assignment as an expression is surprising to the reader and looks like an error. Do not write code like this:

if ( $a = foo() ) {
    bar();
}

Space is cheap, and you're a fast typist, so instead use:

$a = foo();
if ( $a ) {
    bar();
}

Using assignment in a while() clause used to be legitimate, for iteration:

$res = $dbr->query( 'SELECT * FROM some_table' );
while ( $row = $dbr->fetchObject( $res ) ) {
    showRow( $row );
}

This is unnecessary in new code; instead use:

$res = $dbr->query( 'SELECT * FROM some_table' );
foreach ( $res as $row ) {
    showRow( $row );
}

Ternary operator

The ternary operator can be used profitably if the expressions are very short and obvious:

$wiki = isset( $this->mParams['wiki'] ) ? $this->mParams['wiki'] : false;

But if you're considering a multi-line expression with a ternary operator, please consider using an if() block instead. Remember, disk space is cheap, code readability is everything, "if" is English and ?: is not.

String literals

For simple string literals, single quotes are slightly faster for PHP to parse than double quotes. Perhaps more importantly, they are easier to type, since you don't have to press shift. For these reasons, single quotes are preferred in cases where they are equivalent to double quotes.

However, do not be afraid of using PHP's double-quoted string interpolation feature:

$elementId = "myextension-$index";

This has slightly better performance characteristics than the equivalent using the concatenation (dot) operator, and it looks nicer too.

Heredoc-style strings are sometimes useful:

$s = <<<EOT
<div class="mw-some-class">
$boxContents
</div>
EOT;

Some authors like to use END as the ending token, which is also the name of a PHP function. This leads to IRC conversations like the following:

<Simetrical>	vim also has ridiculously good syntax highlighting.
<TimStarling>	it breaks when you write <<<END in PHP
<Simetrical>	TimStarling, but if you write <<<HTML it syntax-highlights as HTML!
<TimStarling>	I have to keep changing it to ENDS so it looks like a string again
<brion-codereview>	fix the bug in vim then!
<TimStarling>	brion-codereview: have you ever edited a vim syntax script file?
<brion-codereview>	hehehe
<TimStarling>	http://tstarling.com/stuff/php.vim
<TimStarling>	that's half of it...
<TimStarling>	here's the other half: http://tstarling.com/stuff/php-syntax.vim
<TimStarling>	1300 lines of sparsely-commented code in a vim-specific language
<TimStarling>	which turns out to depend for its operation on all kinds of subtle inter-pass effects
<werdnum>	TimStarling: it looks like some franken-basic language.

C borrowings

The PHP language was designed by people who love C and wanted to bring souvenirs from that language into PHP. But PHP has some important differences from C.

In C, constants are implemented as preprocessor macros and are fast. In PHP, they are implemented by doing a runtime hashtable lookup for the constant name, and are slower than just using a string literal. In most places where you would use an enum or enum-like set of macros in C, you can use string literals in PHP.

PHP has three special literals: true, false and null. Homesick C developers write null as NULL because they want to believe that it is a macro defined as ((void*)0). This is not necessary.

Use elseif not else if.

PHP pitfalls

  • Understand and read the documentation for isset() and empty(). Use them only when appropriate.
    • empty() is inverted conversion to boolean with error suppression. Only use it when you really want to suppress errors. Otherwise just use !. Do not use it to test if an array is empty, unless you simultaneously want to check if the variable is unset.
    • Do not use isset() to test for null. Using isset() in this situation could introduce errors by hiding mis-spelled variable names. Instead, use $var === null
  • Study the rules for conversion to boolean. Be careful when converting strings to boolean.
  • Be careful with double-equals comparison operators. Triple-equals is often more intuitive.
    • 'foo' == 0 is true
    • '000' == '0' is true
    • '000' === '0' is false
  • Array plus does not renumber the keys of numerically-indexed arrays, so array('a') + array('b') == array('a')
  • Make sure you have error_reporting set to E_ALL | E_STRICT for PHP 5. This will notify you of undefined variables and other subtle gotchas that stock PHP will ignore. See also Manual:How to debug.
  • Don't use the error suppression (@) operator for any reason ever. It's broken when E_STRICT is enabled and it causes an unlogged, unexplained error if there is a fatal, which is hard to support. Use wfSuppressWarnings() and wfRestoreWarnings() instead.

Classes

As a holdover from PHP 4.x's lack of private class members and methods, older code will be marked with comments such as /** @private */ to indicate the intention; respect this as if it were enforced by the compiler.

Use proper visibility in new code, including public if the function could be confused with old code, but do not add visibility to existing code without first checking, testing and refactoring as required, because the above rule has been broken in several places.

Naming

Files

Files which contain include code should be named in UpperCamelCase. Name the file after the most important class it contains; most files will contain only one class, or a base class and a number of descendants. For instance, Title.php contains only the Title class; HTMLForm.php contains the base class HTMLForm, but also the related class HTMLFormField and its descendants.

Name other files, such as JavaScript, CSS, images and SQL, in lowercase. Maintenance scripts are generally in lowerCamelCase, although this varies somewhat. Files intended for the end user, such as readmes, licenses and changelogs, are usually in UPPERCASE.

Never include spaces in filenames or directories, or use non-ASCII characters. For lowercase titles, hyphens are preferred to underscores.

Code elements

Use lowerCamelCase when naming functions or variables. For example:

private function doSomething( $userPrefs, $editSummary )

Use UpperCamelCase when naming classes: class ImportantClass. Use uppercase with underscores for global and class constants: DB_MASTER, Revision::REV_DELETED_TEXT. Other variables are usually lowercase or lowerCamelCase; avoid using underscores in variable names.

There are also some prefixes used in different places:

Functions

  • wf (wiki functions) - Top-level functions, e.g.
    function wfFuncname() { ... }
    

Verb phrases are preferred: use getReturnText() instead of returnText().

Variables

  • wg - global variables, e.g. $wgVersion, $wgTitle. Always use this for new globals, so that it's easy to spot missing "global $wgFoo" declarations. In extensions, the extension name should be used as a namespace delimiter. For example, $wgAbuseFilterConditionLimit, not $wgConditionLimit.
  • m - object member variables: $this->mPage. This is discouraged in new code, but try to stay consistent within a class.

HTTP and session stuff

The following may be seen in old code but are discouraged in new code:

  • ws - Session variables, e.g. $_SESSION['wsSessionName']
  • wc - Cookie variables, e.g. $_COOKIE['wcCookieName']
  • wp - Post variables (submitted via form fields), e.g. $wgRequest->getText( 'wpLoginName' )

Database

  • Table names should be singular nouns: user, page, revision, etc. There are some historical exceptions: pagelinks, categorylinks...
  • Column names are given a prefix derived from the table name: the name itself if it's short, or an abbreviation:
    • pagepage_id, page_namespace, page_title...
    • categorylinkscl_from, cl_namespace...

Common local variables

It is common to work with an instance of the Database class; we have a naming convention for these which helps keep track of the nature of the server to which we are connected. This is of particular importance in replicated environments, such as Wikimedia and other large wikis.

  • $dbw - a Database object for writing (a master connection)
  • $dbr - a Database object for non-concurrency-sensitive reading (may be a read-only slave, slightly behind master state)

Inline documentation

  • The Doxygen documentation style is used (it is very similar to PHPDoc for the subset that we use). For example: giving a description of a function or method, the parameters it takes (using @param), and what the function returns (using @return), or the @ingroup or @author tags.
  • Use "@" rather than "\" as the escape character (e.g. use @param rather than \param) - both styles work in Doxygen, but the @param style works with PHPDoc too, whereas the \param style does not. Use "/**" to begin the comments, instead of the Qt-style formating "/*!".
  • General format for parameters is such: @param $varname [type] [description] so make sure you don't put [type] before $varname:
/**
 * Get the text that needs to be saved in order to undo all revisions
 * between $undo and $undoafter. Revisions must belong to the same page,
 * must exist and must not be deleted
 * @param $undo Revision
 * @param $undoafter Revision Must be an earlier revision than $undo
 * @return mixed string on success, false on failure
 */
public function getUndoText( Revision $undo, Revision $undoafter = null ) {
	$undo_text = $undo->getText();
	$undoafter_text = $undoafter->getText();
	$cur_text = $this->getContent();
	if ( $cur_text == $undo_text ) {
		# No use doing a merge if it's just a straight revert.
		return $undoafter_text;
	}
	$undone_text = '';
	if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) )
		return false;
	return $undone_text;
}

Messages

  • When creating a new message, use hyphens (-) where possible. So for example, "some-new-message" is a good name, while "someNewMessage" and "some_new_message" are not.
  • If the message is going to be used as a label which can have a colon (:) after it, don't hardcode the colon; instead, put the colon inside the message text. Some languages (such as French) need to handle colons in a different way, which is impossible if the colon is hardcoded.
  • HTML class and ID names should be prefixed with "mw-". It seems most common to hyphenate them after that, like "mw-some-new-class" instead of "mw-somenewclass" or "mw-some_new_class", but there doesn't appear to be a clear convention at present.

To do

  • Naming
  • Function parameter choice