The standards and styles are broken down by language, in alphabetical order, with common set of standards listed first. Where possible consistency across language boundaries has been chosen over native language style. Alternatives are given when necessary and for backwards compatibility.
Code spread should be minimized, this means keeping the relevant code in one place and in one language when possible. If there is "more than one way to do it" (and there frequently is) the methodology that will communicate the functionality of the code clearest must be chosen. Processor cycles are relatively inexpensive compared to development team hours dedicated to hunting bugs.
Common
These standards used across all code environments unless specifically defined in a language standard.
- Use Proper Tabs
- ASCII \0x09 not \0x20\0x20 or \0x20\0x20\0x20\0x20
- Terminate Lines with LineFeed
- That is a single \0x0a character, not \0x0d or worse \0x0d\0x0a, unless the code is strictly Windows only, VB, C# and the like
- Use the one true brace style
- Use inline braces for conditionals, loops, nested elements (markup only) and other similar code blocks. Functions (methods) and Class definitions use drop brace
- Comments
- Must be placed in every file to describe it's base functionality and must be placed above any class, function or subroutine definition (use cobj: or func:). Extra comments are encouraged, a list of standard comment phrases is listed below, use
// @code: comment /dev
style, influenced heavily by phpDocumentor - Constants
- Use UPPER_CASE_WIDE_VALUES to define constant values
- Functions, Statics and Variables
- Use the under_score character, or wide_names rather than CamelCase
- Classes and Objects
- Use Wide_Camel_Case for class names, CamelCase names for methods, wide_names for properties
- $Id$ SubVersion Keyword
- If the code is backed in Subversion you must include this keyword in the top five lines of the code file
Comments (You can't grep dead trees)
Comments are necessary to document what is happening and for regulatory compliance for the present and future.
The use of comments is used in favour of extraneous external documentation.
These methods are designed to allow the code to create it's own documentation in the future with simple usage of phpDocumentor and grep
.
This sample below describes the comment codes that are encouraged, they are not case sensitive. Comments should be inserted by starting the comment line according to the language specification for a single line comment, followed by a space, a code from the list below including the trailing colon, a space then the text of the comment. Notice that these are heavily influenced by phpDocumentor.
@version | Original author's name, subsequent authors place their name directly below this. Include a date in this option as shown below. |
@package | Name of the project. |
@link | Point to the projects home page. |
@since | Punch in the version the modifications were started in. |
@todo | Notes for required future development of the code. |
@deprecated | When code pieces are being phased out. |
These are not part of phpDocumentor | |
---|---|
@hack: | This gets the job done now but should not be in the released code, requires futuer cleanup. |
@idea | Notes on how to improve the code, deferred feature request. |
@spec | Descirbes a certian code or business logic specification in effect, point to RFCs, policy, etc. |
@fsff | This code is terrible or non-functional but highly desired, refactor/fix as necessary - soon! |
@copyright | Copyright, if any, on the files contents. |
Common commenting techniques will ensure easy to follow and document code.
# find whats wrong grep -Enr ' @fsff | @idea | @note | @todo ' * # find useful information grep -Enr ' @todo | @hack | @idea | @spec ' # Find API notes grep -Enr ' @param | @method | @return | @var ' * # What to do next grep -Enr ' @fsff | @todo | @hack ' *
Examples specific to each language are shown and should clarify use of this methodolgy. The first example should alos be used as a lingua franca type example, since many other languages are influenced by C/C++
C/C++
Place the required items at the top, follow with any #includes. Prototype every function - small apps should have main() near the top of the core code file with sub routines below.
/**
@author Edoceo Developer - 27 May 2003
@version $Id$
@file src/lib/example.c
*/
// note: includes a bunch of PHP like utility functions, make C like script almost
#include "phpapi.c"
// func: do_something_neat(int arg1, char* arg2) - Does something really great!
// argv: int arg1 - Number of times to do it
// argv: int arg2 - path of file to do it to
void function do_something_neat(int arg1, char* arg2)
{
int i = 0;
while (i < arg1) {
... good code ...
}
}
// func: main() - we don't take no stinking arguments
int main()
{
// @note Comments on IF go right above on single if block
if (pla_is_file("/tmp/cs.xml")) {
do_something_neat(30,"/tmp/cs.xml");
}
// @note should always declare & initialize
int foo = rand_int();
int res = 0;
if (foo_is_bar(foo)) {
// @note multi-branch if should use in-block comment
// Our foo integer is crap, so try one more time
foo = rand_int();
} else {
// @note second and subseqent branches with in-block comment
hook_foo_for_hard_work(foo);
}
// @note switch blocks have in-line comments after the case
switch (res) {
case 1: // Its all good
// @note clearly mark ignore stuff!
// Ignored
break;
case 2: // Its all fail
printf('%d is a failure :(',res));
break;
default: // Should almost always have a default
printf('%d is unexpected',res));
break;
}
// note: never errors
return 0;
}
CSS (and LESS)
- Inline Brace for Rules, Drop Brace on @directives
- The opening brace is on the same line as the rule
- One Line Per Selector
- If a block will apply to multiple selectors, each selector has it's own line terminated with a comma.
- One Line per Declarations
- Each property should be separated from the value by one or more spaces (0x20)
- Use the @media directive
- Use the @media directive when needed but prefer to author in separate files
- Avoid @import directive
- There are many who say this is bad, so we avoid it too
- List Rules is Reverse Specificity Order
- This means listing Elements then Classes then IDs [1], 2]
- List CSS properties in alphabetical order
- Each of the rules, in alphabetical order by their standard names, vendor modifiers immediately follow their standard name
Place grouped element styles, then specific element styles, then IDs then element classes then general classes. Definitions for element groups, single elements, IDs, element classes and general classes must be in alphabetical order. Any comments about a specific element, ID or class should be placed directly above the item.
@media screen {
/* Define Element Group Styles */
a,
h1,
h2 {
border: 1px solid #f00;
}
/* Define Element Styles */
body {
background-color: #fff;
margin: 5px;
}
pre {
border: 1px solid #ccc;
margin: 0px;
padding: 0px;
}
/* Then IDs */
#nav {
margin: 20px;
}
#sub {
background-color: #333;
font-weight: 700;
}
/* Element Classes */
a.bar {
color: #00f;
}
/* General Classes */
.bf {
text-align: center;
}
/* note: field label for forms */
.fl {
text-align: right;
white-space: nobreak;
}
.foo {
font-weight: 700;
}
}
@media print,projection
{
.br { display: none; visibility: hidden; }
}
HTML, XHTML and XML
- Must pass basic XML validation
- If a DTD is present for the document it, of course, must pass this validation.
- Reference the W2C HTML5 Documents
<Root>
<Child>TextValue</Child>
</Root>
Java
We rarely originate projects in Java. Use project originators style, fallback to C/C++ and Common.
JavaScript
- Use jslint on all the code
- Delcare all global vars at the top and indicate usage, g_ prefix is nice.
- Ensure cross browser functionality if needed, favour Mozilla DOM
// $Id$
// auth: email@address.com - 2005-05-20
// file: javascript.js - sitewide javascript routines
var g_active_menu; // (int) indicates which is active
function do_some_activity(e,n)
{
alert('Event ' + e + ' on node ' + n);
n.style.display = 'none';
n.style.visibility = 'hidden';
}
PHP
- Develop with error_reporting(E_ALL)
- A custom error handler is encouraged
- Use {require,include}_once, require preferred over include
// $Id$
// auth: email@address.com - 2005-05-20
// file: sample.php - returns the php info output
error_reporting(E_ALL);
require_once('PEAR.php');
require_once('./my_include.php');
phpinfo();
function some_func($one,$two)
{
if ($one) $x = some_sub_func($one,$two);
elseif ($two)
{
$x = $one + $two;
other_foo_func($x,$one);
}
return $x;
}
PERL
- use strict; is required
- Script should run with no warnings under perl -w
- Define
sub
's at the top and implementmain
below. __BEGIN__
and other constructs are placed after theuse
statements and before anysub
's
#!/usr/bin/perl -w
# file: sample.pl - this script does some stuff
use strict;
# note: i like cookies
my $x = get_fresh_baked_cookies('CC');
# func: get_fresh_baked_cookies - returns a new batch of cookies of the specified type
sub get_fresh_baked_cookies
{
my ($p) = @_;
my @ret = ();
# note: spin up a batch of cookies
for (my $i=0;$i<12;$i++) {
push @ret, $p;
}
return @ret;
}
Shell
Most commonly these will be in a BASH shell, Windows scripting should be done in VBScript.
#!/bin/bash
# note: variables are commonly put in all caps in shell scripts
VAR=somevalue
# func: somefunc - does something
function somefunc
{
return 1
}
SQL
- Write SQL commands in UPPERCASE, like SELECT * FROM table WHERE....
- When possible use parameterized queries, if host language allows
- Avoid usage of triggers
VBScript/ASP
- Must use 'Option Explicit'
- Use of _ is prefered over CamelCase (for consistency with other languages)
- VBScript is not case-sensitive so code in lower case
Option Explicit
' file: sample.asp - copies the data from there to here via bits on a wire
dim var,x
set var = server.createobject("something")
' todo: handle the values less than zero
do while (var.condition=true)
x = var.operation
if (x.value > 0) then
' idea: do something should be error checked
do_some_function(x)
end if
loop
' func: do_some_function() reads data and returns a copy
function do_some_function(byref y)
do_some_function = x + 15
end function
Cleaning Code
It's annoying to clean this but I like nice code.
# Functions with drop-brace
ack 'function\s+\w+[^{]+\s*$'
# Functions with Brace
ack 'function\s+\w+.+\s*{'
# 4 Space Indents
ack '^ '
# Tab Intented
ack '^\t'