User:Avarma/Coding Style

Revision as of 17:38, 15 June 2009 by Avarma (talk | contribs) (added section on closures)

Introduction

My coding style is generally a compromise between the Mozilla JavaScript Style Guide, the vagaries of what js2-mode happens to be compatible with, and my own personal tastes.

Because I started the Jetpack and Ubiquity projects, much of their code happens to conform to this style.

Comments

Comments are always C++-style, starting with a //. This is partly because:

  • It's hard to remember how to format C-style (/* */) lines consistently,
  • Emacs constantly gets confused with C-style comments because there's so many different styles of using them,
  • Virtually all other programming languages use a minor variation on C-style comments, e.g. using # as the comment prefix instead of //, making it easy to convert common comment code (e.g. license blocks) from one language to another,
  • C++-style comments can easily be nested, while C-style comments cannot.

Furthermore, the comments before functions or sections of code are usually commented using WikiCreole syntax, so as to be compatible with Code Illuminated.

Private Variables, Methods, and Closures

It's up to the discretion of the author regarding whether to make private variables/methods "publicly visible" but prefixed with an underscore (_) character, or to contain them in closures. Both have different runtime characteristics, so neither strategy should be followed blindly. Here's some things to keep in mind:

  • Data contained in closures is actually private, which is used by some frameworks like Google Caja to enforce privacy when trusted code interoperates with untrusted code.
  • Code written using closures tends to be more concise and involve less breakage of DRY than code that doesn't use closures.
  • It's very easy to accidentally create memory leaks when using closures.
  • When there's several levels of lexical scope involved in a block of code, reading the code can become confusing.
  • It becomes easier to accidentally introduce bugs into code when the lifetime of a scoped variable is misunderstood. This becomes particularly easy when the code in question uses var instead of let.
  • It's either very difficult or impossible to write unit tests for code that lives inside a closure, or introspect into data contained within a closure when debugging.
  • Code living in a closure is usually duplicated for each instance of the closure that exists, so objects whose private methods are contained in closures often use more memory than objects whose private methods are prefixed with _ and attached to their prototype.
  • Public methods that are contained in closures are usually "detachable" from their parent object in ways that prototype methods aren't, due to the semantics of this.