Best-practices and coding conventions for the CoffeeScript programming language
Switch branches/tags
Nothing to show
Pull request Compare This branch is 20 commits ahead, 10 commits behind polarmobile:master.
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.

AKQA CoffeeScript Style Guide

This guide presents a collection of best-practices and coding conventions for the CoffeeScript programming language.

This guide is intended to be community-driven, and contributions are highly encouraged.

Please note that this is a work-in-progress: there is much more that can be specified, and some of the guidelines that have been specified may not be deemed to be idiomatic by the community (in which case, these offending guidelines will be modified or removed, as appropriate).


The details in this guide have been very heavily inspired by several existing style guides and other resources. In particular:

Table of Contents

## Code layout ### Sublime Text 2 Settings

These settings can be accessing using Command + ,

	"tab_size": 2,
	"translate_tabs_to_spaces": true,
	"trim_trailing_white_space_on_save": true,
	"ensure_newline_at_eof_on_save": true

Properly formatted JSON rules apply.

If Sublime Text is not being used, the following rules should be followed by other means.

### Tabs or Spaces?

Use spaces only, with 2 spaces per indentation level. Never mix tabs and spaces.

### Trailing Whitespace

Do not include trailing whitespace on any lines.

### Blank Lines

Separate top-level function and class definitions with a single blank line.

Separate method definitions inside of a class with a single blank line.

Use a single blank line within the bodies of methods or functions in cases where this improves readability (e.g., for the purpose of delineating logical sections).

Each file should have a newline at the end of the document.

### Encoding

UTF-8 is the preferred source file encoding.

## Classes ### Property and Method Ordering

Your class properties and methods should be ordered from top-down as follows:

  1. Class properties
  2. Base class functions
  3. Public event handlers
  4. Public class functions
### Events

Events should aways:

  • Should start with "on" in the name

     	'click': 'onTrayItemSelected' # Yes
     	'click': 'trayItemSelected' # No
  • Should be past tense

     	'click': 'onTrayItemSelected' # Yes
     	'click': 'onTrayItemSelect' # No
  • Should be camelCase

     	'click': 'onTrayItemSelected' # Yes
     	'click': 'on_tray_item_selected' # No
## Bronson Events

We utilize BronsonJS for our pub/sub.

If subscribing to an event we use a naming pattern like this `subscriber:channel:topic'

In code this would look like.

Bronson.subscribe 'configuratorview:configurator:loaded', (data) ->
  # Do something

To publish an event we use the following naming pattern channel:topic

Bronson.publish 'configurator:loaded'
  message: 'hi'
## Module Imports

If using a module system (CommonJS Modules, AMD, etc.), require statements should be placed on separate lines.

define [
], (Backbone, Bronson, FileName1, FileName2, FileName3, FileName4) ->
  'use strict'

These statements should be grouped in the following order:

  1. Standard library imports (if a standard library exists)
  2. Third party library imports
  3. Local imports (imports specific to this application or library)
## Whitespace in Expressions and Statements

Avoid extraneous whitespace in the following situations:

  • Immediately inside parentheses, brackets or braces

       ($ 'body') # Yes
       ( $ 'body' ) # No
  • Immediately before a comma

       console.log x, y # Yes
       console.log x , y # No

Additional recommendations:

  • Always surround these binary operators with a single space on either side

    • assignment: =

      • Note that this also applies when indicating default parameter value(s) in a function declaration

        test: (param = null) -> # Yes
        test: (param=null) -> # No
    • augmented assignment: +=, -=, etc.

    • comparisons: ==, <, >, <=, >=, unless, etc.

    • arithmetic operators: +, -, *, /, etc.

    • (Do not use more than one space around these operators)

         # Yes
         x = 1
         y = 1
         fooBar = 3
         # No
         x      = 1
         y      = 1
         fooBar = 3
## Comments

If modifying code that is described by an existing comment, update the comment such that it accurately reflects the new code. (Ideally, improve the code to obviate the need for the comment, and delete the comment entirely.)

The first word of the comment should be capitalized, unless the first word is an identifier that begins with a lower-case letter.

If a comment is short, the period at the end can be omitted.

### Header Comments

Header comments apply to the block of code that at the top of each file. Each line of a block comment starts with a # and a single space.

The header should contain:

  • A single #
  • The filename in human readable format
  • A single #
  • A brief description of the overall file
  • A single #
  • A list of authors starting with @authors
  • A single #

An example of a header comment:

  # ClassName
  # The detailed description of this class. The description should
  # outline a high-level overview of the class so any developer
  # can fully understand the responsibilies of the class.
  # This is the second paragraph of the description if needed. All 
  # block-level comments should have a forced wrap to minimize line
  # length.
  # @author Author Name 1, Author Name 2
### Method Comments

Method comments apply to the block of code within a method. Each line of a block comment starts with a # and a single space.

A method comment should contain:

  • A briefe description of the method
  • A single #
  • A list of @param (parameters) with its name, datatype, and description
    • Two spaces should preceed @param followed by the name of the parameter
  • A @return with its returned datatype, and description
    • One space should preceed the @return followed by the description of the return
  # Detailed description of the method. Should be detailed enough for
  # a new developer to be able to fully understand the method and its
  # responsibilies.
  # @param  apple [String] Concise, but detailed description of apple
  # @param  pear [String] Concise, but detailed description of pear
  # @return [String] Description of the returning value
  fooBar: (apple, pear) ->
    combination = apple + pear
### Block Comments

Block comments apply to the block of code that follows them.

Each line of a block comment starts with a # and a single space, and should be indented at the same level of the code that it describes.

Paragraphs inside of block comments are separated by a line containing a single #.

  # This is a block comment. Note that if this were a real block
  # comment, we would actually be describing the proceeding code.
  # This is the second paragraph of the same block comment. Note
  # that this paragraph was separated from the previous paragraph
  # by a line containing a single comment character.

### Inline Comments

Inline comments are placed on the line immediately above the statement that they are describing. If the inline comment is sufficiently short, it can be placed on the same line as the statement (separated by a single space from the end of the statement).

All inline comments should start with a # and a single space.

The use of inline comments should be limited, because their existence is typically a sign of a code smell.

Do not use inline comments when they state the obvious:

  # No
  x = x + 1 # Increment x

However, inline comments can be useful in certain scenarios:

  # Yes
  x = x + 1 # Compensate for border
## Naming Conventions

Use camelCase (with a leading lowercase character) to name all variables, methods, and object properties.

Use CamelCase (with a leading uppercase character) to name all classes. (This style is also commonly referred to as PascalCase, CamelCaps, or CapWords, among other alternatives.)

(The official CoffeeScript convention is camelcase, because this simplifies interoperability with JavaScript. For more on this decision, see here.)

For constants, use all uppercase with underscores:

## Functions

(These guidelines also apply to the methods of a class.)

When declaring a function that takes arguments, always use a single space after the closing parenthesis of the arguments list:

foo = (arg1, arg2) -> # Yes
foo = (arg1, arg2)-> # No

Do not use parentheses when declaring functions that take no arguments:

bar = -> # Yes
bar = () -> # No

In cases where method calls are being chained and the code does not fit on a single line, each call should be placed on a separate line and indented by one level (i.e., two spaces), with a leading ..

  .map((x) -> x * x)
  .filter((x) -> x < 11)
  .reduce((x, y) -> x + y)

When calling functions, choose to omit or include parentheses in such a way that optimizes for readability. Keeping in mind that "readability" can be subjective, the following examples demonstrate cases where parentheses have been omitted or included in a manner that the community deems to be optimal:

baz 12

  x: 10
  y: 20


obj.value(10, 20) / obj.value(20, 10)

print inspect value

new Tag(new Value(a, b), new Arg(c))

$('#selektor').addClass 'klass'
## Strings

Use string interpolation instead of string concatenation:

"this is an #{adjective} string" # Yes
"this is an " + adjective + " string" # No

Prefer single quoted strings ('') instead of double quoted ("") strings, unless features like string interpolation are being used for the given string.

## Conditionals

Favor unless over if for negative conditions.

Instead of using unless...else, use if...else:

  # Yes
  if true

  # No
  unless false

Multi-line if/else clauses should use indentation:

  # Yes
  if true

  # No
  if true then ...
  else ...

Inline if and unless are OK for single conditions (line length considered)

... if [condition]

... unless [condition]
## Looping and Comprehensions

Take advantage of comprehensions whenever possible:

  # Single line
  result = ( for item in array)

  # Multiple Line
  results = []
  for item in array
  # Multiple Line (direct assignment)
  results = for item in array

To filter:

result = (item for item in array when is "test")

To iterate over the keys and values of objects:

object =
  one: 1
  two: 2

alert("#{key} = #{value}") for key, value of object
## Extending Native Objects

Do not modify native objects.

For example, do not modify Array.prototype to introduce Array#forEach.

## Exceptions

Do not suppress exceptions.

## Annotations

Use annotations when necessary to describe a specific action that must be taken against the indicated block of code.

Write the annotation on the line immediately above the code that the annotation is describing.

The annotation keyword should be followed by a colon and a space, and a descriptive note.

  # FIXME: The client's current state should *not* affect payload processing.

If multiple lines are required by the description, indent subsequent lines with two spaces:

  # TODO: Ensure that the value returned by this call falls within a certain
  #   range, or throw an exception.

Annotation types:

  • TODO: describe missing functionality that should be added at a later date
  • FIXME: describe broken code that must be fixed
  • OPTIMIZE: describe code that is inefficient and may become a bottleneck
  • HACK: describe the use of a questionable (or ingenious) coding practice
  • REVIEW: describe code that should be reviewed to confirm implementation

If a custom annotation is required, the annotation should be documented in the project's README.

## Miscellaneous

&& is preferred over and.

|| is preferred over or.

== is preferred over is.

! is preferred over not.

||= is preferred over or=.

temp ||= {} # Yes
temp or= # No
temp = temp || {} # No

Prefer shorthand notation (::) for accessing an object's prototype:

Array::slice # Yes
Array.prototype.slice # No

Prefer @property over

return @property # Yes
return # No

However, avoid the use of standalone @:

return this # Yes
return @ # No

Avoid return where not required, unless the explicit return increases clarity.

Use splats (...) when working with functions that accept variable numbers of arguments:

console.log args... # Yes

(a, b, c, rest...) -> # Yes