Guest User

Untitled

a guest
May 3rd, 2016
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.41 KB | None | 0 0
  1. Whether you use 2 spaces or 4 spaces, there are a few simple things that can make your node.js code easier to read. We've been using them in all the hapi modules for over 4 years now to great results. This list is by no means complete but it highlights the most useful elements that will give you immediate value in reducing bugs.
  2.  
  3. ### Required modules
  4.  
  5. JavaScript makes it harder than most languages to know where variables are coming from. Variables assigned required modules are particularly important because they represent a singleton object shared with the entire application. There are also globals and module globals, along with function variables and arguments.
  6.  
  7. Traditionally, variables starting with an uppercase letter represent a class that must be instantiated using `new`. This was an important semantic in the early days of JavaScript but at this point, if you don't know `Date` requires `new Date()` you are probably very new. We have adopted Upper Camel Case variable names for all module global variables which are assigned required modules:
  8.  
  9. ```js
  10. var Hapi = require('hapi');
  11. ```
  12.  
  13. Note that you cannot `new Hapi()`, only `new Hapi.Server()`. In this style, the exported object from the modules always exposes an object which contains the API. This means a single function module should still export an object with the single method as an object property:
  14.  
  15. ```js
  16. exports.add = function (a, b) {
  17.  
  18. return a + b;
  19. };
  20. ```
  21.  
  22. This makes it trivial to identify which variables in your code represent required modules. The language itself does contain a few uppercase variables but those are well known and should not cause any confusion.
  23.  
  24. ### Module classes
  25.  
  26. When a module (any node.js file) contains its own prototype class, that class variable also starts with an uppercase which can cause confusion. However, we do not allow any module global variable except for one: `internals` (and of course whatever node.js provides).
  27.  
  28. ```js
  29. var Hapi = require('hapi');
  30.  
  31. var internals = {};
  32.  
  33. internals.Server = function () {
  34.  
  35. this.server = new Hapi.Server();
  36. this.server.connection();
  37. };
  38.  
  39. internals.server = new internals.Server();
  40.  
  41. // This is not allowed:
  42.  
  43. var server = new internals.Server();
  44. ```
  45.  
  46. This means that within any function in your code, uppercase variables are either required modules APIs or JavaScript natives. Any `internals` prefixed variables are module globals which act as a singleton. The rest are either function variables or arguments which are easier to spot because of the smaller scope.
  47.  
  48. A note about singletons - I often see bugs caused by developers using a module global variable used by a prototype. For example:
  49.  
  50. ```js
  51. var internals = {};
  52.  
  53. internals.storage = {};
  54.  
  55. exports.Cache = internals.Cache = function () {
  56.  
  57. };
  58.  
  59. internals.Cache.prototype.get = function (key) {
  60.  
  61. return internals.storage[key];
  62. };
  63.  
  64. internals.Cache.prototype.set = function (key, value) {
  65.  
  66. return internals.storage[key] = value;
  67. };
  68. ```
  69.  
  70. The problem is that multiple instances of the cache will all share the same memory:
  71.  
  72. ```js
  73. var Cache = require('./cache');
  74.  
  75. var cache1 = new Cache();
  76. var cache2 = new Cache(); // Uses the same memory cache1 uses
  77. ```
  78.  
  79. By requiring the use of `internals` as a prefix, this bug becomes obvious to spot. When I code review a pull request, I always search for all the instances of `internals` to make sure it only holds static configuration and other safe data to share between instances. This is much harder to spot without the prefix.
  80.  
  81. ### Callback new lines
  82.  
  83. Understanding your code flow is critical in asynchronous development. Consider this:
  84.  
  85. ```js
  86. internals.read = function (db, key, callback) {
  87. db.get(key, function (err, value, meta) {
  88. if (err) {
  89. return callback(err);
  90. }
  91.  
  92. if (meta.age > 10000) {
  93. return callback(null, null);
  94. }
  95.  
  96. return callback(null, value);
  97. });
  98. };
  99. ```
  100.  
  101. At a quick glance, it is not obvious that the `db.get()` method is asynchronous. It looks just like any other scope indentation. By adding a new line after every function declaration, we make the callbacks "pop" and much easier to spot:
  102.  
  103. ```js
  104. internals.read = function (db, key, callback) {
  105.  
  106. db.get(key, function (err, value, meta) {
  107.  
  108. if (err) {
  109. return callback(err);
  110. }
  111.  
  112. if (meta.age > 10000) {
  113. return callback(null, null);
  114. }
  115.  
  116. return callback(null, value);
  117. });
  118. };
  119. ```
  120.  
  121. Allowing your eyes to immediately identify those line breaks means you can quickly note where your code switched event loop ticks.
  122.  
  123. ### `return` callbacks
  124.  
  125. You might have noticed that every `callback()` call is prefixed with `return`. This is a defensive programming tool. It provides both a visual cue where in the code execution ends and returned up the stack, but also protection against adding code later after that point that can create timing issues, race conditions, or multiple callback calls.
  126.  
  127. It is sometimes helpful to add a `return` when it is not obvious a nested function contains a callback. Consider the example above, it can be made safer with an extra `return` either in front of the method:
  128.  
  129. ```js
  130. internals.read = function (db, key, callback) {
  131.  
  132. return db.get(key, function (err, value, meta) {
  133.  
  134. if (err) {
  135. return callback(err);
  136. }
  137.  
  138. if (meta.age > 10000) {
  139. return callback(null, null);
  140. }
  141.  
  142. return callback(null, value);
  143. });
  144. };
  145. ```
  146.  
  147. or immediately after (usually with a comment):
  148.  
  149. ```js
  150. internals.read = function (db, key, callback) {
  151.  
  152. db.get(key, function (err, value, meta) {
  153.  
  154. if (err) {
  155. return callback(err);
  156. }
  157.  
  158. if (meta.age > 10000) {
  159. return callback(null, null);
  160. }
  161.  
  162. return callback(null, value);
  163. });
  164.  
  165. return; // db.get() invokes the callback
  166. };
  167. ```
  168.  
  169. ### `callback` vs `next`
  170.  
  171. There are many cases where a callback doesn't have to be called on the next tick for performance or workflow reasons. However, that can create an unpredictable API where it is not clear in which tick the callback is invoked. To make it explicit, I use `callback` when it is guaranteed the callback is called on another tick, and `next` when it can be both. It is a simple naming convention that has made maintaining hapi much simpler over many months.
  172.  
  173. ```js
  174. exports.a = function (a, b, callback) {
  175.  
  176. return process.nextTick(function () {
  177.  
  178. return callback(null, a + b);
  179. });
  180. };
  181.  
  182. exports.b = function (a, b, next) {
  183.  
  184. return next(null, a + b);
  185. };
  186. ```
Add Comment
Please, Sign In to add comment