JavaScript coding conventions

From PKP Wiki
Revision as of 21:20, 13 December 2010 by Jerico.dev (Talk | contribs)

Jump to: navigation, search

Google Coding Conventions

We use Google's JavaScript style guide as a starting point for our own style guide.

Only deviations from the Google style guide will be documented here.

JsDoc Comments

We use class/member-level JsDoc comments as outlined in the Google style guide but we replace the file-level annotations by our usual annotations (@file, @brief, etc.).

Generally we encourage inline comments. These help readers of your code to understand the logic without having to understand every line of code. It's also a good practice to write inline comments before you write code so that you first think about the logic and semantics you want to implement and then about the syntax.

For the moment being we do not use curly braces ({}) around the object declared with @extends. This is for better tool support. The build script will introduce the braces for compilation.

Whitespace

We generally use whitespace exactly as outlined in Google's JavaScript style guide except for indentation which we do with tabs rather than spaces.

Object Oriented Programming in JS

Inheritance

There are many ways to implement inheritance in JavaScript. We chose our approach for flexibility, simplicity and memory/execution performance.

We are using a (pseudo-)classical approach of inheritance rather than the purely prototypical or mixin approach:

// Define parent constructor.
Parent = function() { ... };
// Implement parent object.
Child.prototype.xyz = ...;

// Define child constructor.
Child = function() { ... };

// Let Child inherit from Parent - memory efficient version avoiding constructor side effects.
Temp = function() {};
Temp.prototype = Parent.prototype;
Child.prototype = new Temp();
// + a bit of sugar to fix the constructor property and allow access to the parent prototype...

// Implement child object.
Child.prototype.xyz = ...;

Compared with the 'purely' prototypical approach (parent = {...}; F = function() {}; F.prototype = parent; child = new F;):

  • It's easier to put in an intermediate object above the parent when we use constructors from the beginning.
  • It's easy to insert initialization code in the parent object if required at a later stage because we won't have to insert new everywhere in the code.
  • There's minimal overhead in using functions as parents if we make sure to not call the constructor (thereby avoiding potential side effects of the constructor and making a potentially big object) when letting a child inherit from the parent, see use of 'Temp' above.

Compared with the pure "mixin" approach (used in jQuery and jQueryUI):

  • Easy access to superclass method implementations via our custom _parent static variable.
  • Using new is usually faster than manually copying mixins to new objects in a loop.
  • You cannot use the instanceof operator with Mixins.
  • Mixins are less memory efficient than inheritance via prototypes.

Cross-Cutting Concerns

There are certain features that are really cross-cutting concerns or that should be shared between objects independent of their inheritance hierarchy. JavaScript fortunately has very powerful mechanisms to deal with such situations.

While we do not use "mixins" to implement vertical code re-use (see inheritance above), we use them throughout to implement horizontal code re-use. Objects "declare" the aspects they implement similarly to how they declare inheritance - via a method that actually implements the mixin.

We implement cross-cutting aspects in separate objects and then introduce them into classes. We have got two mechanisms for that:

  1. interface weaving
  2. interceptors

Interfaces

There is no syntactical correspondence for interfaces in JavaScript but we implement them conceptually as objects and enforce them with the Closure compiler. We have an "abstract" base object that declares the methods that go into an interface without implementing them. Then we let implementations of the interface inherit from these "abstract" objects.

Interfaces that share the same implementation across objects can be weaved into objects as aspects via our $.Helper.injectMixin() method which relies on our object factory to identify the right implementation of an interface and then introduces it into the target object via the mixin mechanism provided by jQuery's $.extend() mechanism. This allows us to exchange interface implementations on runtime without having to change the object declarations, see the explanation of the object factory below.

If the interface implementation differs on a per-object basis so that we cannot use shared mixins then objects implement it themselves.

Method Interception

We can implement method interception via the proxy that we attach to every object on instantiation. The proxy can either implement methods itself or delegate to other objects for actual interception. We'll further detail that design approach when we actually need it.

Object Factory

The object factory introduces an additional indirection between client code and the objects it instantiates. Without an object factory, client code would have to be closely coupled to specific implementations of certain interfaces on object instantiation. The object factory allows us to work with logical "object names" rather than "class names". We then can control in one central place how these object names will be resolved to actual objects. The performance overhead for such an approach is minimal in JavaScript as, due to the dynamic nature of JavaScript, we can use very powerful native JavaScript functionality.

Potential use cases of such an approach are: - dynamic dependency injection (IoC) - run-time weaving of interfaces and method interceptors (AOP) - a central place to enforce restrictions and application policies on object level

This indirectly introduces more flexible possibilities for logging, security/consistency checks, dynamic patching of objects, central configuration, improved testability, working with stub implementations, etc.

Visibility

All our object members are techically public.

We use the @constructor, @protected and @private markers that Google's JavaScript compiler understands and enforces.

We also put underscores in front of object members that are intended to be private.

Advantages over the 'closure + privileged method approach' (see e.g. Douglas Crockford, "JavaScript: The good parts") for private object members:

  • Reduced complexity for novice programmers who are not so familiar with the closure concept.
  • Approach is similar to our PHP4 compatible nomenclature for private methods in PHP.
  • Less probability to create memory leaks with closures, see http://code.google.com/speed/articles/optimizing-javascript.html
  • Better tool support (e.g. Eclipse JSDT)


Object vs. 'Class' members

There is no such thing as classes (or static methods) in JavaScript. We implement class members that do not need to be copied into each object instance (=static members) within the constructor object:

SomeConstructor = function() { ... };
SomeConstructor.staticMethod = function() { ... };

Thereby we make sure that on instantiation of that constructor with the new keyword, staticMethod will not be copied into the new object instance.

NB: Inheritance of 'static' object members is not supported!


Object member ordering

We group object members by visibility and singleton ('static') vs. instance membership in the following order in our object definitions:

  1. constructor (use @constructor annotation)
  2. private static variables (start with underscore, use @private annotation)
  3. private instance variabes (start with underscore, use @private annotation)
  4. protected instance variables (discouraged, better use private variables with protected accessors/mutators, use @protected annotation)
  5. no public static/instance variables - use public accessors/mutators instead!
  6. public static methods
  7. public methods
  8. protected static methods (use @protected annotation)
  9. protected methods (use @protected annotation)
  10. private static methods (start with underscore, use @private annotation)
  11. private methods (start with underscore, use @private annotation)

Sections are divided with a three line // style comment indicating the class member category.

You are obviously not supposed to use a member outside its scope even if the visibility is not enforced by closure. Please run lib/pkp/tools/buildjs.sh on your code to make sure that you have not overlooked anything. This is also true for protected object members. While they are named like public methods they must not be used outside of the inheritance hierarchy of the current class.


Building and Checking JS Code

Build Script

We have developed a build script that serves several purposes:

  • Run checkers over the code that make sure that we implement a safe subset of JavaScript. We use JSLint and the Google Linter for that purpose. The checking process will also enforce most of our coding style rules, including some additional annotation-based type checking that is not implemented in JavaScript itself.
  • Join, compile and minify the source. This is necessary to reduce the number of files to be loaded on a web page as well as the overall size of the JavaScript files. It has an important performance impact on page load.

The build script is in lib/pkp/tools/buildjs.sh. It can be run whenever changes have been made in the code to check whether these are compatible with our coding style guide. The script also makes sure that the differences from the Google coding style guide will not come in the way. Please look at the source code for further information. The script has extensive inline documentation.

NB: Currently only files in the js/classes folder will be checked against our coding style rules. External files in lib and legacy files in functions contain too many deviations from the expected coding style for such a check being useful there. We should, however, make sure that we include at least the files in functions sooner or later.

Switch Between Minified and Original Code

We now have a new parameter in config.inc.php that is used to switch between the minified version and the full version of the code. The parameter is called enable_minified.

For production environments this parameter should always be set to "On". You can only set it to on after executing the build script.

For development environments the parameter can be switched "Off" for easier in-browser debugging, e.g. via FireBug. This allows you to step through the original source code rather than having to decipher the minified code.

Adding New Scripts Files

Whenever you create a new JavaScript source file you must add it to the templates/common/minifiedScripts.tpl file. This file has two purposes:

  • It will be included as a whole into the header template when enable_minified is switched to "Off".
  • It will be parsed by the build script to discover files to be minified and/or checked.

Code Release

The build script must be run before we release code so that an up-to-date minified source file will be included in the released tar archive. We also should make sure that we release code with the enable_minified parameter already switched to "On" in config.TEMPLATE.inc.php.


Additional Resources

Recommended Books

  • Ross Harmes and Dustin Diaz, "Pro JavaScript Design Patterns"
  • Douglas Crockford, "JavaScript: The Good Parts"

Recommended Articles