Web Coding Conventions

2012-03-10

This is a very basic set of web coding conventions aimed to maintain code consistency.

Indentation and Formatting

  • Indentation is done with 4 spaces, not tabs. (Why?)
    • For consistent display.
    • For use in entry areas that are not tab-enabled (i.e., textareas).
    • For simplicity.
  • Indent style is K&R Variant: 1TBS
  • Files are UTF-8 encoded (no BOM).
  • Line breaks are in UNIX format (LF: Line Feed, U+000A, chr(10), \n).
  • Lines of code do not exceed 120 characters in all reasonable circumstances.
  • Excessive source formatting (e.g., vertical alignment) is avoided.
  • More detailed formatting conventions can be seen in the examples at the end of this document.

Documentation

Source code is generously commented. Inline documentation systems are used (i.e., phpDoc, Doxygen, etc.).

Naming Conventions

  • lower_case_underscore
    • Variables (not properties), including instantiated objects (not properties)
    • Functions (not methods)
    • Associative array keys
    • Non-public file and directory names
  • lower-case-hyphen
    • Public file and directory names (Why?)
      • For SEO purposes, because Google does not see an underscore as a word separator.
    • CSS selectors (class and id) (Why?)
      • For consistency with pseudo-classes and microformats.
      • For use with the selector: E[foo|="en"]
  • UPPER_CASE
    • Constants
  • CamelCase
    • Class names
  • lowerCamelCase
    • Methods
    • Properties

Additional notes:

  • Private and protected variables begin with an underscore.
  • Camel-cased acronyms remain camel-cased (i.e., getHtml, getDbTable, etc.).
  • true, false, and null are lowercase.

Third-Party Conventions

When using a third-party script, library, or framework, the standards and conventions of that script, library, or framework should be used (when appropriate).

For example, when I build an application with CodeIgniter, I stick to my own conventions because the application code is encapsulated in the "application" directory, and because the CodeIgniter conventions are so contrary to mine. On the other hand, if I were to build a community library for CodeIgniter, I would use the CodeIgniter conventions 100%.

Markup and CSS

  • The HTML5 doctype is used.
  • All tags are closed.
  • Self-closing elements have a space before the forward slash.
  • Boolean attributes are fully written: required="required"
  • Tags and attributes are lowercase.
  • Attribute values are quoted with double quotes.
  • Inline styles are avoided, except for: style="display: none;"
  • A CSS reset is used to avoid cross-browser style conflicts.
  • CSS validation errors related to -moz*, -khtml*, -webkit*, and opacity are acceptable.

Examples

HTML5 Template

<!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title>HTML5 Template</title> <meta name="description" content="An HTML5 Template" /> <meta name="author" content="Bo Allen" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/4.0.0/normalize.min.css" type="text/css" /> <link rel="stylesheet" href="/css/styles.css" type="text/css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> <!--[if lt IE 9]> <script src="https://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> </body> </html>

CSS

/* ELEMENTS */ body { color: #345; padding: 5px; } h1 { font-size: 22px; color: #fff; background: #345; padding: 2px; } h2 { border-bottom: 1px solid #345; } p { margin-left: 10px; } code { display: block; white-space: pre-wrap; margin: 20px 0; padding: 10px; border: 1px solid #6784a1; background: #f0f0e4; } /* TEMPLATE */ div#container { font-family: verdana, helvetica, sans; font-size: .9em; } div#content { margin: 0 20px 0 240px; } /* COMMON CLASSES */ .error { color: red; font-weight: bold; background: pink; } .clear { clear: both; } .toggle-info { width: 75%; display: none; background: #dde; margin: 5px; border: 1px solid #dde; }

JavaScript

$(document).ready(function() { // Click handler for confirm submit buttons $('input[type=submit].confirm').click(function() { var actionText; if ($(this).attr('title')) { actionText = $(this).attr('title'); } else { actionText = 'submit this form'; } return confirm('Are you sure you want to ' + actionText + '?'); }); });

PHP Class

<?php /** * A simple car class example. * * Usage example: * require_once 'Car.php'; * $lambo = new Car('Lamborghini', 'Countach', 'ZA9CA05A8JLA12353', array('xm_radio' => true, 'nitrous' => true); * echo $lambo->getOption('nitrous'); * * @author Bo Allen http://boallen.com */ class Car { /** * The make (i.e., Ford, Honda, etc.) * * @var string */ public $make; /** * The model (i.e., Focus, Civic, etc.) * * @var string */ public $model; /** * The VIN * * @var string */ private $_vin; /** * Car options * * @var array */ protected $_options; /** * Car class constructor * * @param string $make The make of the car (i.e., Honda) * @param string $model The model of the car (i.e., Civic) * @param string $_vin (Optional) The VIN. * @param array $_options (Optional) Car options */ public function __construct($make, $model, $_vin = '', $_options = array()) { $this->make = $make; $this->model = $model; $this->_vin = $_vin; $this->_options = $_options; } /** * Returns the car make * * @return string */ public function getMake() { return $this->make; } /** * Returns the car model * * @return string */ public function getModel() { return $this->model; } /** * Returns the VIN * * @return string */ private function _getVin() { return $this->_vin; } /** * Returns a car option * * @param string $key The option name * @return mixed */ protected function _getOption($key) { if (isset($this->_options[$key])) { return $this->_options[$key]; } else { return false; } } }

PHP Function

<?php /** * Returns a true random number from RANDOM.ORG's integer * http interface. Requires cURL. * * @author Bo Allen * @param int $min (Optional) Minimum number (default 1) * @param int $max (Optional) Maximum number (default 100) * @return mixed Random number (int) on success, error or message (string) on failure */ function get_true_random_number($min = 1, $max = 100) { // Validate parameters $max = ((int) $max >= 1) ? (int) $max : 100; $min = ((int) $min < $max) ? (int) $min : 1; // Curl options $options = array( CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => false, CURLOPT_FOLLOWLOCATION => true, CURLOPT_ENCODING => '', CURLOPT_USERAGENT => 'PHP', CURLOPT_AUTOREFERER => true, CURLOPT_CONNECTTIMEOUT => 120, CURLOPT_TIMEOUT => 120, CURLOPT_MAXREDIRS => 10, ); // Curl init & run $ch = curl_init('http://www.random.org/integers/?num=1&min=' . $min . '&max=' . $max . '&col=1&base=10&format=plain&rnd=new'); curl_setopt_array($ch, $options); $content = curl_exec($ch); curl_close($ch); return trim($content); }