wiki:CodingStyle

Version 8 (modified by Frederico Caldeira Knabben, 16 years ago) (diff)

Added "File Headers"

Coding Style Guidelines

Those guidelines where defined based on mixed common standards mainly related to Java and C# programming.

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 style" syntax, it has nothing to do with it. It is not a class based language. It is an interpreted, object based, loosely typed scripting language. It can run only in the presence of a "host" application, like a web browser.

If we instead take a closer look at C# code standards (from Microsoft), we'll not more modern and readable proposals, which help also on identifying custom code from the underlying host environment.

The following definitions are based on long years of experience with pure JavaScript coding.

General Recommendations

Any violation to the guide is allowed if it enhances readability.

The name "FCKeditor" is used, it must always be written with "FCK" uppercased concatened 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

Names representing packages must be in CamelCase. Whenever applicable, the package name will be prefixed with "FCKeditor.".

    FCKeditor, FCKeditor.Net, FCKeditor.Java

Names representing public classes and public global objects must be in CamelCase and prefixed with "FCK".

    FCKBrowserInfo, FCKToolbarButton

Names representing constants must be all uppercase.

    FCK_STATUS_COMPLETE, FCK_EDITMODE_WYSIWYG, CTRL

Names representing public methods must be verbs and written in CamelCase.

    AppendStyleSheet(), GetElementDocument(), 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

Names representing private global function must be in CamelCase prefixed with an underscore.

    function _DoSomething()

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 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 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 )

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 pascalCase.

    function Sum( firstNumber, secondNumber )

Local variables must be in pascalCase.

    function DoSomething()
    {
        var colorOne = 1 ;
        var colorTwo = 2 ;

        return colorOne + colorTwo ;
    }

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 
     */                            */

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.

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:

/*
 * FCKeditor - The text editor for Internet - http://www.fckeditor.net
 * Copyright (C) 2003-2007 Frederico Caldeira Knabben
 *
 * == BEGIN LICENSE ==
 *
 * Licensed under the terms of any of the following licenses at your
 * choice:
 *
 *  - GNU General Public License Version 2 or later (the "GPL")
 *    http://www.gnu.org/licenses/gpl.html
 *
 *  - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
 *    http://www.gnu.org/licenses/lgpl.html
 *
 *  - Mozilla Public License Version 1.1 or later (the "MPL")
 *    http://www.mozilla.org/MPL/MPL-1.1.html
 *
 * == END LICENSE ==
 *
 * [File Description]
 */

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.


© 2003 – 2022, CKSource sp. z o.o. sp.k. All rights reserved. | Terms of use | Privacy policy