Coding standards i use
Consistency
- If a codebase uses functions named do_stuff() or doStuff(), then this method must be followed.
- If functions are named subject_action() or action_subject(), then this must also be followed.
Following the projects naming and code style and conventions takes precedence over all following rules.
If and While blocks
For a single if/while clause with a short set of conditions a single line can be used, but it must never span multiple lines
This:
if(condition) do_stuff();
Not this:
if(condition) do_stuff();
else do_other_stuff();
Like this
if(condition) {
do_stuff();
} else {
do_other_stuff();
}
Single line blocks
Concise, readable and self-documenting
Self-documenting and readable
This
function squareRootApproximation(n) {
var r = n / 2;
while ( abs( r - (n/r) ) > t ) {
r = 0.5 * ( r + (n/r) );
}
return r;
}
print("r = " + squareRootApproximation(r));
Not this
// square root of n
r = n / 2;
while ( abs( r - (n/r) ) > t ) {
r = 0.5 * ( r + (n/r) );
}
print("r = " + r);
Jeff Atwood of codinghorror.com has also written about this.
Long lines
I split long lines onto multiple lines. I do not have a maximum line length but i try to keep it around 100 characters. Lines with comments on the same line can be more than 100 characters.
Example:
SELECT column1,
column2,
column3,
column1+column2+column3 AS sum
FROM table
WHERE sum < ?
Or
DELETE FROM table WHERE sum >= ?
Or
UPDATE table
SET sum=column1+colum2+column3
WHERE column1 IS NOT NULL AND
column2 IS NOT NULL AND
column3 IS NOT NULL
For SQL I’ve developed a personal style: I right align the keyword so that all parameters start in the same column for the whole statement. I am not aware of anyone else following this style but would be intersted in any opinions.
Indentation
I adapt to the indentation that is used for the platform/project I’m working on (rule #1: consistency). I prefer spaces over tabs because it is more likely to present the code in the same way person reading the code. However there are good reasons to indent otherwise and rule #1: consistency takes precedence here also.
Blocks must always be indented!
class Foo {
function do_stuff() {
if(!condition) return;
calculate_stuff()
}
Except when it contains a single block it can be placed on the level, or even line. The package {} block contains only one block (the class). Indenting this block would result in unnessecary indentation of the WHOLE program.
For example (in Flex).
package {
class Foo {
function do_stuff() {}
}
}
Similarly, in XML i place CDATA blocks on the same line:
<mx:Script><![CDATA[
function() {
do_stuff();
}
]]></mx:Script>
blog comments powered by Disqus