(→File Headers) |
|||
(11 intermediate revisions by 2 users not shown) | |||
Line 4: | Line 4: | ||
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 | 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 == | + | == General Recommendations == |
− | Any violation to the guide is allowed if it enhances readability. | + | 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. | + | If the name "CKEditor" is used, if must always be written with "CKE" uppercased concatenated with "ditor" in lowercase. The following usages are wrong: "CKeditor", "ckEditor", "CK Editor", etc. Exceptions are made for directories and file names, which must always be lowercased, and the CKEDITOR namespace name. |
+ | |||
+ | 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. | The name "JavaScript" should be written with both the "J" and "S" in uppercase. The following are wrong: "Javascript", "javascript", etc. | ||
Line 84: | Line 86: | ||
} | } | ||
</pre> | </pre> | ||
− | Single statement if/else/while/for could (preferably) be written without brackets, but never in the same line. | + | Single statement (single line only) if/else/while/for could (preferably) be written without brackets, but never in the same line. |
<pre>if ( condition ) | <pre>if ( condition ) | ||
statement; | statement; | ||
Line 117: | Line 119: | ||
</pre> | </pre> | ||
=== Whitespace === | === Whitespace === | ||
− | + | "If", "for", "while" and "switch" should be followed by a white space. | |
+ | <pre>if ( true ) | ||
+ | NOT | ||
+ | if( true ) | ||
+ | </pre> | ||
Conventional operators should be surrounded by a space (including ternary operators). | Conventional operators should be surrounded by a space (including ternary operators). | ||
<pre>if ( i > 3 && test == 'yes' ) | <pre>if ( i > 3 && test == 'yes' ) | ||
Line 139: | Line 145: | ||
<pre>if ( myVar == 1 ) | <pre>if ( myVar == 1 ) | ||
</pre> | </pre> | ||
+ | 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: | ||
+ | <pre>(function() | ||
+ | { | ||
+ | // Code here | ||
+ | })(); | ||
+ | |||
+ | myMethod( function() | ||
+ | { | ||
+ | // Code here | ||
+ | }); | ||
+ | </pre> | ||
Functions/method calls should not be followed by a space. | Functions/method calls should not be followed by a space. | ||
<pre>doSomething( someParameter ); | <pre>doSomething( someParameter ); | ||
Line 160: | Line 177: | ||
// Apply rotation | // Apply rotation | ||
transformation.multiply( matrix ); | transformation.multiply( matrix ); | ||
+ | </pre> | ||
+ | |||
+ | Multiple variables declaration in a single "var" statement must be aligned with a single tab. | ||
+ | |||
+ | <pre> | ||
+ | var example = 1, | ||
+ | sample = 2; | ||
+ | NOT | ||
+ | var example = 1, | ||
+ | sample = 2; | ||
</pre> | </pre> | ||
Line 177: | Line 204: | ||
return colorOne + colorTwo; | return colorOne + colorTwo; | ||
} | } | ||
− | </pre> | + | </pre> |
− | Several variables can be defined with a single var statement, but only if their initialization values are in single lines: | + | 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: |
− | <pre>var someVar, | + | <pre>var aVar, someVar, |
− | + | other1Var = 10, | |
+ | other2Var = 25, | ||
isVar = true; | isVar = true; | ||
Line 194: | Line 222: | ||
</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 block *This is a block |
− | * comment. | + | * comment. *comment |
− | */ | + | */ */ |
</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 == | ||
Line 217: | Line 246: | ||
Other than shortnesses and better readability, regular expression literals are compiled during script evaluation, which improves performance at runtime. | Other than shortnesses and better readability, regular expression literals are compiled during script evaluation, which improves performance at runtime. | ||
− | == File Headers == | + | == String Literals == |
+ | |||
+ | When defining string literals, use single quotes instead of double quotes, whenever possible. | ||
+ | |||
+ | <pre>var s = 'Some text'; | ||
+ | NOT | ||
+ | var s = "Some text"; | ||
+ | </pre> | ||
+ | |||
+ | == 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. | + | 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: | + | Here is a JavaScript template for the header to be included in the source code: |
<pre>/* | <pre>/* | ||
− | + | Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. | |
− | + | For licensing, see LICENSE.html or http://ckeditor.com/license | |
− | + | */ | |
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
</pre> | </pre> | ||
− | Of course, different languages have different commenting syntax, so it is enough to copy the header from an existing file to maintain the style. | + | 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 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 [http://producingoss.com/en/managing-volunteers.html#territoriality Producing Open Source Software]: | + | 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 [http://producingoss.com/en/managing-volunteers.html#territoriality Producing Open Source Software]: |
− | <blockquote> | + | <blockquote>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?<br> </blockquote> <blockquote> |
− | 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?<br> | + | 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?<br> |
− | </blockquote> <blockquote> | ||
− | 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?<br> | ||
</blockquote> | </blockquote> | ||
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. | 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. |
Latest revision as of 11:23, 2 January 2012
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 "CKEditor" is used, if must always be written with "CKE" uppercased concatenated with "ditor" in lowercase. The following usages are wrong: "CKeditor", "ckEditor", "CK Editor", etc. Exceptions are made for directories and file names, which must always be lowercased, and the CKEDITOR namespace name.
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 (single line only) 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
"If", "for", "while" and "switch" should be followed by a white space.
if ( true ) NOT if( true )
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 );
Multiple variables declaration in a single "var" statement must be aligned with a single tab.
var example = 1, sample = 2; NOT var example = 1, sample = 2;
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.
String Literals
When defining string literals, use single quotes instead of double quotes, whenever possible.
var s = 'Some text'; NOT var s = "Some text";
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-2012, 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.