wiki:CodeStyle

Code Style

This is just a random, unordered and incomplete list of the common code style issues and the way they've been handled in Spam Board. If you make modifications / additions, it'd be great if you stuck to this style in order to keep it as consistent as possible. I'm not trying to start yet another holy war, much of this is just personal preference, but it has been started this way.

Indentation

Use tabs. Rationale: let everybody decide how widely indented they want their code. In the middle of a line, use spaces instead, because different tab sizes will screw it up there.

Example

$blah = 42;
if (isset($blah) && $bla > 0) {
[TAB]$var_name1 = TRUE;
[TAB]$n[SPACES] = 5;
}

Columns

No limit. Rationale: Let the text editor do soft wrapping. Also, tabs and hard wrapping don't really mix well, as different tab sizes interfere with a fixed maximum width.

Line Breaks

Use LF (or \n, if you prefer that notation), not CR or even CR/LF. There are text editors for every operating system which support this.

Variables

Global variables which are valid in more than one function / class should be written all in uppercase. Variables which are valid throughout a longer function should be in lowercase. Variables which are valid only in one loop (or whatever) can start with an underscore.

Try to use descriptive names, unless your variable has a lifetime of only very few lines (even then, it can't hurt).

Common Names

  • $i, $j: counters
  • $n: total number of something
  • $q, $q2 and so on: database queries
  • $row, $row2...: result set returned by database query
  • $C: database connection
  • $F: global formatting object

Initialization

Initialize variable on their first occurence. Don't immediately start by adding or appending something to them. If it's some sort of input, check if the variable exists.

Example

$string = '';
$i = 0;
while (isset($input) && $input === TRUE) {
    $string .= 'blah';
    $i++;
}

Functions

Use underscores to delimit words in the function name. Use lowercase only. There are no functions in Spam Board. Try to keep it this way.

Example

function do_something_very_cool() {
}

Classes

Capitalize the first letter of a class name.

Methods

Use camelCase for method names (but keep the initial letter lowercase).

Example

class Blah {
    function doSomethingVeryCool() {
    }
}

Braces

Even if you only have one statement after if, for or whatever, use braces (it avoids some of the most annoying errors). Put the opening brace in the same line as the control statement and the closing brace in its own line (on the same indentation level as the control statement)

Example

if (isset($n) && is_numeric($n)) {
    for ($i = 0; $i < $n; $i++) {
        $j--;
    }
}

File Header

Copy & paste the header from another file and adapt it.

Example

/**
 * Package: Spam Board 5
 * File: index.php
 * Description: wrapper file calling all the others directly or indirectly
 *
 * Copyright (C) 2007 Hannes Schueller
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, version 3 of the
 * License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program (see LICENCE). If not,
 * see <http://www.gnu.org/licenses/>.
 **/

Inline Code

Never write anything outside the opening (<?php) and closing (?>) PHP angle brackets.

Output

Add any output to the $html member variable of the page object. Never use echo or print.

Punctuation

Use a space after commas, semicolons and such. Glueing strings together, put a space before and after the dot delimiter, and do the same for <, >, =, && and such.

Example

for ($i = 0; $i <= $n; $i++) {
    $string .= 'blah' . $var;
}

Quotes

Per default, use single quotes for strings, unless you want to use single quotes within. Never put variables to be evaluated between double quotes (even though this works), but close the string first and append the variable with a dot. Rationale: Looks a lot cleaner, works better with highlighting of all text editors.

Example

$string = $var1 . 'something' . $var2 . "using 'single quotes'" . $var3;

Comments

Use C++ style comments () for one-liners and C-style comments (/* */) for quotes over more than one line. Avoid Perl style comments (#).

Comment your code thoroughly (yes, this is hard, because it's all so obvious, but it helps others tremendously). Function and method declarations have their own header describing name, input, output and purpose.

Example

/**
 * Function:    make_profit
 * Input:       $input - array containing the private e-mail addresses of all users
 * Returns:     boolean value to indicate success
 * Description: write the data into a file which is suitable for selling to a spam provider
 **/
function make_profit($input) {
    // check, if enough addresses have been cumulated
    if (count($input) > 12345) {
        // it's worth it
        return TRUE;
    } else {
        // not enough yet
        return FALSE;
    }
}

/* this is a very long comment which just goes on and on and on and on and on and on and on,
 * so that at some point, I decided to do a hard line break to keep it readable */
$success = make_profit($stuff);
if ($success) {
    // better clean up...
    hide_evidence();
}

Keywords

Write TRUE, FALSE and NULL in uppercase.

Readability

Avoid inline conditions (condition?do:else) and compressed shortcuts ($array[$i++] = $var).

Example

if (condition) {
    do
} else {
    else
}

$i++;
$array[$i] = $var;

SQL

Write SQL keywords in uppercase. Never just put variables in SQL statements. Let PDO escape them via bindValue and bindParam. Whenever possible, fetch results as an object, not as an array. Try to keep it cross-database compatible...

Example

$q = $C->prepare('SELECT memberemail FROM ' . $SETTINGS['dbtableprefix'] . 'members WHERE memberstatus = :status AND memberid > :one ORDER BY memberid ASC');
$q->bindParam(':status', $_status, PDO::PARAM_STR);
$q->bindValue(':one', 1, PDO::PARAM_INT);
$q->execute();
while ($row = $q->fetchObject()) {
    spam_member($row->memberemail);
}
Last modified 9 years ago Last modified on 08/03/08 09:18:10