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:
- PEP-8: Style Guide for Python Code
- Bozhidar Batsov's Ruby Style Guide
- Google's JavaScript Style Guide
- Common CoffeeScript Idioms
- Thomas Reynolds' CoffeeScript-specific Style Guide
- Jeremy Ashkenas' code review of Spine
- The CoffeeScript FAQ
- The CoffeeScript Style Guide
Use spaces only, with 2 spaces per indentation level. Never mix tabs and spaces.
### Maximum Line LengthLimit all lines to a maximum of 79 characters where possible. If it is necessary to have lines longer than 79 characters, that is acceptable as long as it is kept to a minimum.
### Blank LinesSeparate 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).
### Trailing WhitespaceDo not include trailing whitespace on any lines.
### EncodingUTF-8 is the preferred source file encoding.
## Module ImportsIf using a module system (CommonJS Modules, AMD, etc.), require
statements should be placed on separate lines.
These statements should be grouped in the following order:
- Standard library imports (if a standard library exists)
- Third party library imports
- Local imports (imports specific to this application or library)
In terms of our Spine project, here is a slightly expanded version of that order:
- Global modules
- SDK/non-app modules
- Shared app modules
- Spine controllers
- Spine models
- Spine views
Within each category, try to keep the list ordered alphabetically and by path.
Every Spine level object should have a suffix with the type of object it is:
- ThingView for eco templates
- ThingModel for models
- ThingController for controllers
Any instance of an object should be in lower case (e.g. service).
Any class should be the same as the class name, with suffix if a spine object (e.g. OrgModel).
Any import of constants should be in ALL_CAPS_WITH_UNDERSCORE (e.g. EVENT_TYPE).
Imports should each be on a separate line to make our diffs easier to read and merges less painful.
An example of correct imports in our Spine application (using AMD style):
define [
'app/shared/event_types'
'app/lib/session'
'app/controllers/orgs'
'app/models/vapp'
'app/views/titlebar'
], (
EVENT_TYPE
session
OrgsController
VappModel
TitleBarView
) ->
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:
=
-
An exception is 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
-
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.
### Block CommentsBlock 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.
init()
start()
stop()
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
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.)
Classes should be named without any type information in the name. Class not ClassModel. Classes referring to lists or collections of things should have their names pluralized.
class Class # Yes
class ClassModel # No
class Classes # Yes
class ClassList # No
For constants, use all uppercase with underscores:
CONSTANT_LIKE_THIS
Methods and variables that are intended to be "private" should begin with a leading underscore:
_privateMethod: ->
File names should be all lower case separate with underscore:
file_name.coffee
(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 .
.
[1..3]
.map((x) -> x * x)
.concat([10..12])
.filter((x) -> x < 11)
.reduce((x, y) -> x + y)
When calling functions, include parentheses unless you are passing a single multi-line object to a function.
baz(12)
bar.init
x: 10
y: 20
z: 210
foo(4).bar(8)
obj.value(10, 20) / obj.value(20, 10)
print(inspect(value))
new Tag(new Value(a, b), new Arg(c))
Be careful about chaining when having called more than one function without parentheses:
# GOOD: no problem here, since there is only one function call
# on the first line.
service.post(url, ConstantsSdk.JSON_CONTAINER_CONTENT_TYPE, request, opts)
.then(successCallback, failedCallback)
# BAD: newer version of coffeescript thinks the .then() applies
# to the result of deferreds.push(), not service.post().
deferreds.push service.post(url, ConstantsSdk.JSON_CONTAINER_CONTENT_TYPE, request, opts)
.then(successCallback, failedCallback)
# GOOD: previous example fixed with dangling paren.
deferreds.push(
service.post(url, ConstantsSdk.JSON_CONTAINER_CONTENT_TYPE, request, opts)
.then(successCallback, failedCallback)
)
# GOOD: another way to fix.
callback = service.post(url, ConstantsSdk.JSON_CONTAINER_CONTENT_TYPE, request, opts)
.then(successCallback, failedCallback)
deferreds.push(callback)
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.
Favor unless
over if
for negative conditions.
Instead of using unless...else
, use if...else
:
# Yes
if true
...
else
...
# No
unless false
...
else
...
Multi-line if/else clauses should use indentation:
# Yes
if true
...
else
...
# No
if true then ...
else ...
Take advantage of comprehensions whenever possible:
# Yes
result = (item.name for item in array)
# No
results = []
for item in array
results.push item.name
To filter:
result = (item for item in array when item.name is "test")
To iterate over the keys and values of objects:
object = one: 1, two: 2
alert("#{key} = #{value}") for key, value of object
Do not modify native objects.
For example, do not modify Array.prototype
to introduce Array#forEach
.
Do not suppress exceptions.
## AnnotationsUse 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.
resetClientState()
processPayload()
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.
analyze()
Annotation types:
TODO
: describe missing functionality that should be added at a later dateFIXME
: describe broken code that must be fixedOPTIMIZE
: describe code that is inefficient and may become a bottleneckHACK
: describe the use of a questionable (or ingenious) coding practiceREVIEW
: 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.
## Miscellaneousand
is preferred over &&
.
or
is preferred over ||
.
is
is preferred over ==
.
not
is preferred over !
.
or=
should be used when possible:
temp or= {} # Yes
temp = temp || {} # No
Prefer shorthand notation (::
) for accessing an object's prototype:
Array::slice # Yes
Array.prototype.slice # No
Prefer @property
over this.property
.
return @property # Yes
return this.property # 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