Bo Allen's Web Coding Standards
This is a very basic set of web coding standards aimed to maintain code consistency.
General Practices
Indentation and Line Breaks
All indentation is done with 4 spaces, not tabs.
Why spaces?
Line breaks must be in UNIX format (LF: Line Feed, U+000A, chr(10), \n).
Maximum Line Length
Lines of code should not exceed 120 characters.
Naming Conventions
Everything falls into one of five of the following naming conventions:
- lower_case_underscore
- PHP variables (not properties)
- PHP functions (not methods)
- Associative array keys
- CSS selectors (class and id)
- Non-public file and directory names
- lower-case-dash
- Public file and directory names (Why?)
- UPPER_CASE
- Constants
- CamelCase
- Class names
- lowerCamelCase
- Objects
- Methods
- Properties
An underscore (not a dash) replaces a space.
Private and protected variables begin with an underscore.
Indent Style
K & R Style: Variant 1TBS
http://en.wikipedia.org/wiki/Indent_style#Variant:_1TBS
function favorite_indent_style($style) {
if ($style != '1TBS') {
return false;
} else {
return true;
}
}
Cross Browser Testing
The latest versions of the following browsers should be tested for compatibility.
- Firefox
- IE (7, and 8)
- Chrome
- Safari
Be aware that as of April 2009, statistics show that as much as 10% of all browser traffic is still IE6. Testing is at your discretion.
Third-Party Development
When using a third-party framework or library, the coding standards of that framework or library should be used.
HTML
Doctype
XHTML 1.0 Transitional will be used (until HTML5 is solidly supported (2012? 2022?)).
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Valid XHTML 1.0 Transitional Template</title> </head> <body> </body> </html>
Layout
The div element is to be used for layout elements. HTML tables are intended for tabular data only.
All div elements with an id attribute must be marked at the closing div. See
the example below.
<div id="header">
<h1>Title</h1>
</div> <!-- /#header -->
Self-closing Elements
A space is required before the forward slash of a self-closing element.
<br />
<br/>
Tags and Attributes
All tags and attributes must be written in lowercase. Additionally, it is preferred that any attribute values also be lowercase, when the purpose of the text therein is only to be interpreted by machines. For instances in which the data needs to be human readable, proper title capitalization should be followed, such as:
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<a href="http://example.com/" title="Description Goes Here">Example.com</a>
Quotes
In keeping with the strictness of XHTML code conventions, according to the W3C, all attributes must have a value, and must use double-quotes. The following are examples of proper and improper usage of quotes and attribute/value pairs.
<input type="text" name="email" disabled="disabled" />
<input type=text name=email disabled>
CSS
Inline Styles
Inline style attributes are not allowed (style="..."). Internal style declarations are allowed when they
make sense. Please use external stylesheets.
An exception to this rule is style="display: none;" for revealing hidden elements via JavaScript.
CSS Validation
All cascading stylesheets should be verified against the W3C validator, to ensure correct syntax and to check for possible accessibility issues with text and background colors. This in and of itself is not directly indicative of good code, but it helps to weed out problems that are able to be tested via automation. It is no substitute for manual code review.
Validation errors related to -moz*, -khtml*, -webkit*, and opacity should be considered "warnings" rather than errors. Just be sure to cross-browser test your styles.
CSS Formatting
To ease potential headaches for maintenance, all CSS must be written in a consistent manner. For one, all CSS selectors must be listed on their own line. As a general rule of thumb, if there is a comma in CSS, it should immediately be followed by a line break. This way, we know that all text on a single line is part of the same selector. Likewise, all property/value pairs must be on their own line with standard indentation (4 spaces), and end with a semicolon. All property values must begin with a space (after the colon). The closing brace must be on the same level of indentation as the selector that began it - flush left.
#selector-1 span,
#selector-2 span,
#selector-3 span {
background: #fff;
color: #000;
}
#selector_1 span, #selector_2 span, #selector_3 span {
background:#fff; color: #000
}
#selector { background: #fff; color: #000; }
Pixels vs. Ems
Use the px unit of measurement to define font size, because it offers absolute control over text.
Using the em unit for font sizing used to be popular, to accommodate for Internet Explorer 6 not
resizing pixel based text. However, all major browsers (including IE7 and IE8) now support text resizing of pixel
units and/or full-page zooming. Since IE6 is largely considered deprecated, pixels sizing is preferred.
Additionally, unit-less line-height is preferred because it does not inherit a percentage value of its parent element,
but instead is based on a multiplier of the font-size.
Do not use the pt unit for screen media (i.e., print only).
.selector {
font-size: 13px;
line-height: 1.5;
}
.selector {
font-size: 0.813em;
line-height: 1.25em;
}
Internet Explorer Bugs
Inevitably, when all other browsers appear to be working correctly, any and all versions of Internet Explorer will introduce a few nonsensical bugs, delaying time to deployment. While it is we encouraged to troubleshoot and build code that will work in all browsers without special modifications, sometimes it is necessary to use conditional if IE comments to serve up specific fixes, which are ignored by other browsers.
<!--[if IE 7]> <link type="text/css" rel="stylesheet" href="/assets/styleshseets/ie7.css" /> <![endif]--> <!--[if IE 8]> <link type="text/css" rel="stylesheet" href="/assets/styleshseets/ie8.css" /> <![endif]-->
Shorthand
In general, CSS shorthand is preferred because of its terseness, and the ability to later go back and add in values that are already present, such as the case with margin and padding. Developers should be aware of the TRBL acronym, denoting the order in which the sides of an element are defined, in a clock-wise manner: Top, Right, Bottom, Left. If bottom is undefined, it inherits its value from top. Likewise, if left is undefined, it inherits its value from right. If only the top value is defined, all sides inherit from that one declaration.
For more on reducing stylesheet code redundancy, and using CSS shorthand in general:
- http://qrayg.com/journal/news/css-background-shorthand
- http://sonspring.com/journal/css-redundancy
- http://dustindiaz.com/css-shorthand
Margin & Padding
#selector {
margin: 0 0 10px;
padding: 0 0 10px;
}
#selector {
margin: 0 0 10px 0;
padding: 0 0 10px 0;
}
Hex Colors
We prefer hex values for all colors, written in lower-case. No upper-case or RGB, please! Additionally, all colors should be written as tersely as possible. This means that colors such as full blue, which can be written lengthily as #0000FF, should be simply written as #00f. Obviously, for colors that require more precision, all six characters should be used. For example, a light shade of grayish beige: #f9f9f0.
Background
#selector {
background: #fff url(../images/file.png) repeat-x fixed left bottom;
}
#selector {
background-color: #fff;
background-image: url(../images/file.png);
background-repeat: repeat-x;
background-attachment: fixed;
background-position: left bottom;
}
Border
In general, border should be a single line declaration, assuming that the values of the border are the same on all sides of the element. The order in which values are declared are: width, style, and color.
#selector {
border: 1px solid #000;
}
If the values of each side differ, then there are two possible ways of using shorthand, and it is up to the discretion of the developer to decide which to use. Note that method 2 follows the TRBL pattern.
#selector {
border-color: #fff #999 #666 #ccc;
border-style: solid dashed dotted double;
border-width: 1px 2px 3px 4px;
}
#selector {
border-top: 1px solid #fff;
border-right: 2px dashed #999;
border-bottom: 3px dotted #666;
border-left: 4px double #ccc;
}
Font
Not to be confused with the inadvisable <font> tag, the CSS font property can be written in a few different ways. The shorthand property puts all the aspects of the font into a single declaration, whereas the longhand splits it out over several lines. While the contrast between methods is not as stark as with that of the border property, there is still space to be saved by using shorthand. While line-height can be defined within the scope of the font declaration, but when written in longhand it has its own unique property.
Times New Roman is encapsulated in quotes, because the font name itself contains spaces.
#selector {
font: italic small-caps bold 15px/1.5 Cambria, 'Times New Roman', sans-serif;
}
#selector {
font-style: italic;
font-variant: small-caps;
font-weight: bold;
font-size: 15px;
line-height: 1.5;
font-family: Cambria, 'Times New Roman', sans-serif;
}
Longhand
When overriding only parts of a style, longhand declaration is preferred. This way, by sticking to shorthand for initial style declarations, anytime a longhand declaration used, it could be deduced that it is overriding only a very precise part of an overall style, thereby leaving other aspects unaffected.
#selector {
border: 1px solid #ccc;
font: 11px Verdana, sans-serif;
}
#selector.modifier {
border-bottom-color: #333;
border-bottom-width: 2px;
font-family: Georgia, serif;
}
Javascript
Type Coercion
Unlike strongly typed languages such as Java or C#, JavaScript will perform type coercion when evaluating conditional statements. This sometimes creates awkward scenarios in which numerical values are seen as false or the existence of a string is mistaken for true. This is typically disadvantageous.
To ensure a strict level of comparison, as might be seen in a strongly typed or compiled language, JavaScript (like PHP) has a triple-equals operator ===. In similar fashion, it also has a strict negation operator !==. Consider the following examples of potential pitfalls when it comes to evaluating comparisons.
var test_1 = 'true';
var test_2 = 0;
if (test_1 == true) {
// Code here will run. But it shouldn't.
}
if (test_1 === true) {
// Code here won't run. Correct behavior.
}
if (test_2 != false) {
// Code here won't run. But it should.
}
if (test_2 !== false) {
// Code here will run. Correct behavior.
}
As you can see in the example above, simply using == and != is insufficient because it makes for potentially unpredictable results. Therefore, the stricter comparison operators should always be used. There is never a good reason to use the lesser form of comparison operators. To simply for the existence of elements in the DOM, there is an even more abbreviated way, that leaves no room for ambiguity. If you are unsure if certain elements will be present in an HTML page, use one of the following techniques.
function first_func() {
if (!document.getElementById('id_name')) {
return;
}
// If code gets here, element exists.
}
function second_func() {
if (!document.getElementsByTagName('div').length) {
return;
}
// If code gets here, one or more exist.
}
Whitespace
In general, the use of whitespace should follow longstanding English reading conventions. I.e., there will be one space after each comma and colon (and semi-colon where applicable), but no spaces immediately inside the right and left sides of parenthesis. In short, we advocate readability within reason. Additionally, braces should always appear on the same line as their preceding argument.
Consider the following examples of a JavaScript for-loop...
for (var i=0, j=arr.length; i<j; i++) {
// Do something.
}
for ( var i = 0, j = arr.length; i < j; i++ )
{
// Do something.
}
Variables
All JavaScript variables shall be written in lowerCamelCase, because every variable in Javascript is a property of an object.
Quotes
The preferred method of delineating strings is to use single quotes for everything. Since JavaScript exists to manipulate markup, and because HTML is generally written with double quotes in W3C specifications, using single quoted strings will better facilitate handling HTML fragments, and keep code more readable.
var my_html = '<img class="photo" src="/path/file.jpg" alt="Text" />';
var my_html = "<img class=\"photo\" src=\"/path/file.jpg\" alt=\"Text\" />";
Event Listeners
Rather than using attributes such as onload, onfocus, onsubmit, or onclick directly in markup, we will instead attach event listeners to these elements via unobtrusive techniques. The reasoning for this is the same philosophy that is behind not using inline declarations. So doing inextricably ties the behavior of a web page to its data, and makes maintenance more difficult.
Event Delegation
When assigning unobtrusive event listeners, it is typically acceptable to assign the event listener directly to the element(s) which will trigger some resulting action. However, occasionally there may be multiple elements which match the criteria for which you are checking, and attaching event listeners to each one might negatively impact performance. In such cases you should use event delegation instead.
Closures & Scope
To maintain proper scope for variables, it is highly recommended that self-executing anonymous function be used as a closure. For the most part, variables defined correctly using the var syntax, within the scope of a function will not add to global scope pollution. However, from time to time, you may need to access variables via two or more functions. In such cases, multiple functions can be grouped together inside a closure.
(function() {
var first_variable = 'value 1';
var second_variable = 'value 2';
function first_func() {
// Do something.
}
function second_func() {
// Do something.
}
})();
Objects & Arrays
Objects can be thought of as tiered variables that contain multiple attributes. Similarly, an array could be described as a list of data that all share common characteristics. The following code snippets show examples of objects and arrays, and the different ways in which they can be defined. Note that values such as John Doe's age and marital status do not have quotation marks around them. This is because age is truly numerical, and true is a Boolean value.
Note also that the commas are before the variable or method declaration. This prevents errors with trailing commas in IE and other browsers.
Objects (and arrays) are an important part of JSON - JavaScript Object Notation, which is a platform and language independent way of transmitting data, used as an alternative to XML.
var john_doe = {
first_name: 'John'
,last_name: 'Doe'
,job: 'Everyman Respresentative'
,email: 'john.doe@example.com'
,married: true
,age: 30
};
/*
Could also be written:
var john_doe = new Object();
*/
var john_doe = {};
john_doe.first_name = 'John';
john_doe.last_name = 'Doe';
john_doe.job = 'Everyman Representative';
john_doe.email = 'john.doe@example.com';
john_doe.married = true;
john_doe.age = 30;
var doe_family = [
'John'
,'James'
,'Jane'
,'Jenny'
,'Jared'
,'Jerome'
];
/* Could also be written: var doe_family = new Array(); */ var doe_family = []; doe_family[0] = 'John'; doe_family[1] = 'James'; doe_family[2] = 'Jane'; doe_family[3] = 'Jenny'; doe_family[4] = 'Jared'; doe_family[5] = 'Jerome';
PHP
General
- Beginning brackets do NOT line break. They start one space after the end parenthesis, as according to traditional Unix policy.
- Do not do any real logic in object constructors. Create class methods to do so.
- true, false, and null should always be lowercase.
Javascript booleans are lowercase and case-sensitive. - Avoid embedded assignments (ex: $d = ($a = $b + $c) is bad).
- Use && and || instead of AND and OR.
- Never use extract().
- Avoid using global variables if at all possible.
- Document EVERYTHING.
Parenthesis
- Do not put parenthesis next to keywords. Put a space between.
- Do not use parenthesis when using include, require, include_once, and require_once.
- Do not use parenthesis in return statements when it's not necessary.
- Do put parenthesis next to function names.
- Examples:
require_once './config.php';
if ($test) {
// ...
}
if (!$test) {
// ...
}
while ($test == $other) {
// ...
}
array_push($one, $two);
return $test;
Classes, Methods, and Properties
- All class names are CamelCase
- All method names will be lowerCamelCase.
- All private and protected methods and properties must be prefixed with the underscore _ character.
class Car {
public $make;
public $model;
private $_vin;
protected $_options;
public function __construct($make, $model, $_vin, $_options) {
$this->make = $make;
$this->model = $model;
$this->_vin = $_vin;
$this->_options = $_options;
}
public function getMake() {
return $this->make;
}
public function getModel() {
return $this->model;
}
private function _getVin() {
return $this->_vin;
}
protected function _getOptions() {
return $this->_options;
}
}
Functions and Variables
All functions and variables (non-object) will be lower_case.
$user_bio = "I am a ninja, not a pirate.";
function filter_user_bio($bio) {
str_replace('pirate', '******');
}
Arrays
- Array index names use the underscore _, not the dash as their separator. This prevents errors with magic_quotes.
- Array index names are always lowercase. Spaces are represented by an underscore.
- Array index names are always encapsulated with single quotes.
Example:$user['salt'] = 'iodized';
Constants
- Constants must be in all UPPERCASE letters.
- Use only if absolutely necessary.
File Structure
- Public file names and directories are lower-case with dashes.
(For SEO purposes, because Google does not see an underscore as a separator.) - Non-public file names and directories are lower_case with underscores.
- PHP class files should be in the format: ClassName.class.php (FormValidator.class.php).