User:Avarma/Coding Style: Difference between revisions

added section on closures
(added section on comments)
(added section on closures)
Line 15: Line 15:


Furthermore, the comments before functions or sections of code are usually commented using [http://www.wikicreole.org/ WikiCreole] syntax, so as to be compatible with [http://www.toolness.com/wp/?p=441 Code Illuminated].
Furthermore, the comments before functions or sections of code are usually commented using [http://www.wikicreole.org/ WikiCreole] syntax, so as to be compatible with [http://www.toolness.com/wp/?p=441 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 (<tt>_</tt>) 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 [http://code.google.com/p/google-caja/ 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 [http://en.wikipedia.org/wiki/Don%27t_repeat_yourself DRY] than code that doesn't use closures.
* It's very easy to accidentally create [http://jibbering.com/faq/faq_notes/closures.html 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 <tt>var</tt> instead of <tt>let</tt>.
* 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 <tt>_</tt> 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 <tt>this</tt>.
93

edits