Line 206: | Line 206: | ||
</pre> | </pre> | ||
− | == Comments == | + | == Comments == |
− | Tricky code should not be commented but rewritten: In general, the use of comments should be minimized by making the code self-documenting by appropriate name choices and an explicit logical structure. | + | Tricky code should not be commented but rewritten: In general, the use of comments should be minimized by making the code self-documenting by appropriate name choices and an explicit logical structure. |
− | All comments should be written in English. Whenever possible, end comments with a period as normal phrases, and wrap comments within the first 80 characters of each line. | + | All comments should be written in English. Whenever possible, end comments with a period as normal phrases, and wrap comments within the first 80 characters of each line. |
− | There should be a space after the comment identifier. | + | There should be a space after the comment identifier. |
− | <pre> | + | <pre>// This is a comment. NOT: //This is a comment |
− | // This is a comment. NOT: //This is a comment | ||
/** NOT: /** | /** NOT: /** | ||
* This is block *This is a block | * This is block *This is a block | ||
Line 220: | Line 219: | ||
*/ */ | */ */ | ||
</pre> | </pre> | ||
+ | Note that comment blocks should be opened with two asterisks only for documentation purposes. See [[FCKeditor 3.x/Design and Architecture/Documentation#JavaScript_API|JavaScript API Documentation]]. | ||
+ | |||
== Regular Expressions == | == Regular Expressions == | ||
Revision as of 17:12, 17 February 2009
Contents
Coding Style Guidelines
These guidelines where defined based on mixed common standards mainly related to Java programming. It aims to reflect the generally accepted standards for JavaScript coding with some minor adjustments.
It is quite common to take the Java style to write JavaScript code, assuming it is a "cut-down" version of Java. Although JavaScript has an indirect relation with Java, apart from the similar "C
General Recommendations
Any violation to the guide is allowed if it enhances readability.
If the name "FCKeditor" is used, it must always be written with "FCK" uppercased concatenated with "editor" in lowercase. The following are wrong: "FckEditor", "FCKEditor", "fckEditor", "FCK Editor", and so on. Exception is made for directory names, where all chars "should" be in lowercase.
The name "JavaScript" should be written with both the "J" and "S" in uppercase. The following are wrong: "Javascript", "javascript", etc.
Naming Conventions
Generic Name Conventions
The ROOT namespace has a fixed name: CKEDITOR.
CKEDITOR
Names representing namespaces must be all lowercase.
CKEDITOR.dom, CKEDITOR.env, CKEDITOR.ui
Names representing public classes and public global objects must be in PascalCase.
CKEDITOR.dom.Document, CKEDITOR.Util
Names representing constants must be all UPPERCASE.
CKEDITOR.STATUS_COMPLETE, CKEDITOR.EDITMODE_WYSIWYG, CKEDITOR.CTRL
Names representing public methods must be verbs and written in camelCase.
appendStyleSheet(), getElement (), setTimeout()
Names representing public properties must be nouns and written in camelCase.
name, document, targetWindow
Names representing private methods must be verbs and written in camelCase prefixed with an underscore.
_doInternalStuff()
Names representing private properties must be nouns and written in camelCase prefixed with an underscore.
_internalCounter, _prefix
Abbreviations and acronyms should not be uppercase when used as name.
setHtml(), XmlDocument NOT setHTML(), XMLDocument
All names should be written in English.
Specific Name Conventions
The prefixes "get" and "set" may be used on methods that get or set properties which require computation.
setArrayCount(), getFormattedValue()
The prefix "checkIs" may be used on methods which return boolean states which require computation.
checkIsValid(), checkIsEmpty()
Abbreviations in names should be avoided.
getDirectoryName(), applicationCommand NOT getDirName(), appCmd
Files
All files must be named in all lower case.
Classes and global objects should be declared in individual files with the file name matching the class/object name.
fckbrowserinfo.js, fcktoolbarbutton.js
Layout
For indentation, the TAB should be used. Development IDEs should be configured to represent TABs as 4 spaces.
if ( test ) { if ( otherTest ) doSomething(); doMore(); }
Block layout should be as illustrated.
while ( !done ) { doSomething(); done = moreToDo(); }
Single statement if/else/while/for could (preferably) be written without brackets, but never in the same line.
if ( condition ) statement; while ( condition ) statement; for ( initialization ; condition ; update ) statement;
The above rule is not valid for nested blocks, like the following:
if ( condition ) { if ( anotherCondition ) statement; } // WRONG: if ( condition ) if ( anotherCondition ) statement;
The incompleteness of split lines must be made obvious.
totalSum = a + b + c + d + e; method( param1, param2, param3 ); setText( 'Long line split' + 'into two parts.' );
Whitespace
Conventional operators should be surrounded by a space (including ternary operators).
if ( i > 3 && test == 'yes' )
Commas should be followed by a space.
function myFunction( parm1, param2, param3 )
Semi-colons in for statements should be surrounded by a space.
for ( var i = 0 ; i < count ; i++ )
Semi-colons should not be preceded by a space.
doSomething(); var name = 'John';
Colons should be surrounded by a space.
case 100 : NOT case 100:
Opening parenthesis must be followed by a space and closing parenthesis must be preceded by a space.
if ( myVar == 1 )
There special cases where no space is recommended. When opening parenthesis for a "self-executing anonymous function" and when closing parenthesis after an indented code block:
(function() { // Code here })(); myMethod( function() { // Code here });
Functions/method calls should not be followed by a space.
doSomething( someParameter ); NOT doSomething ( someParameter );
Logical units within a block should be separated by one blank line.
// Create a new identity matrix var matrix = new Matrix4x4(); // Precompute angles for efficiency var cosAngle = mathCos( angle ); var sinAngle = mathSin( angle ); // Specify matrix as a rotation transformation matrix.setElement( 1, 1, cosAngle ); matrix.setElement( 1, 2, sinAngle ); matrix.setElement( 2, 1, -sinAngle ); matrix.setElement( 2, 2, cosAngle ); // Apply rotation transformation.multiply( matrix );
Variables
Variables must be always defined with "var".
Function parameters must be in camelCase.
function sum( firstNumber, secondNumber )
Local variables must be in camelCase.
function doSomething() { var colorOne = 1; var colorTwo = 2; return colorOne + colorTwo; }
Several variables can be defined with a single var statement, but only if their initialization values are in single lines. Do not initialize more than one variable is a single line:
var aVar, someVar, other1Var = 10, other2Var = 25, isVar = true; var longVar = function() { // This var takes more than one line. }; var objVar = { // This var takes more than one line. };
Comments
Tricky code should not be commented but rewritten: In general, the use of comments should be minimized by making the code self-documenting by appropriate name choices and an explicit logical structure.
All comments should be written in English. Whenever possible, end comments with a period as normal phrases, and wrap comments within the first 80 characters of each line.
There should be a space after the comment identifier.
// This is a comment. NOT: //This is a comment /** NOT: /** * This is block *This is a block * comment. *comment */ */
Note that comment blocks should be opened with two asterisks only for documentation purposes. See JavaScript API Documentation.
Regular Expressions
The regular expression literal should be used whenever possible, instead of the RegExp object, which should be used only when the regular expression pattern is not constant or depends on runtime computation.
/^foo\s*/i NOT new RegExp( '^foo\s*', 'i' )
Other than shortnesses and better readability, regular expression literals are compiled during script evaluation, which improves performance at runtime.
File Headers
There are minimum requirements for us to be able to make our code available to the world. Most of them are related to legal needs, which help us protecting the project from abuses.
Here is a JavaScript template for the header to be included in the source code:
/* Copyright (c) 2003-2009, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */
Of course, different languages have different commenting syntax, so it is enough to copy the header from an existing file to maintain the style.
Author Tags
Author names, e-mails or web site addresses should be avoided in the header. To justify that, let me recall a citation from Sander Striker, a member of the Apache Software Foundation, that can be found at Producing Open Source Software:
At the Apache Software foundation we discourage the use of author tags in source code. There are various reasons for this, apart from the legal ramifications. Collaborative development is about working on projects as a group and caring for the project as a group. Giving credit is good, and should be done, but in a way that does not allow for false attribution, even by implication. There is no clear line for when to add or remove an author tag. Do you add your name when you change a comment? When you put in a one-line fix? Do you remove other author tags when you refactor the code and it looks 95% different? What do you do about people who go about touching every file, changing just enough to make the virtual author tag quota, so that their name will be everywhere?
There are better ways to give credit, and our preference is to use those. From a technical standpoint author tags are unnecessary; if you wish to find out who wrote a particular piece of code, the version control system can be consulted to figure that out. Author tags also tend to get out of date. Do you really wish to be contacted in private about a piece of code you wrote five years ago and were glad to have forgotten?
The SVN is a good place to understand user participation. Even when committing changes proposed by Joe White, it is nice to add a comment like "Thanks to Joe White." in the commit message.