GitHub LinkedIn RSS
Sunday, April 27, 2014

Modular Design Patterns in JavaScript


Last week we've discussed how to create classes and namespaces in JavaScript. For those who missed it, you can read it here. There is however something else you need to know regarding the topic, which is modules.

Modules


When we say an application is modular, we generally mean it's composed of a set of highly decoupled, distinct pieces of functionality stored in modules. Module can and are implemented using classes, which we already know how to define. So what is the problem? When you try to build a complex piece of software, you end up with hundreds of classes. All of them somehow interact with one another and since JavaScript is not compiled, your job is to reference and load these classes in a correct order. This is why module loaders specification was invented - the most prominent of which are CommonJS and AMD.

CommonJS


Currently, CommonJS is a de facto standard. Many third-party vendors are making modules or module-load systems according to the CommonJS module specification. Node.js is a typical project that complies with the specification. CommonJS is a voluntary working group organized to use JavaScript not only in browser, but also in server-side and desktop applications.

Definition


If you're are Node.js developer, you've already used CommonJS syntax numerous times, without knowing it. There are other CommonJS implementation, however since Node.js is the most popular and wide spread technology, I'll use it in my examples. Recall our JsDeepDive.Common.Utils class from the previous post. Let's create a module from it using CommonJS syntax:
(function () {
 'use strict';

 var Utils = function () {
  var privateMember = 1,
  privateFuncA = function privateFuncA() {
   return 'privateFuncA';
  },

  privateFuncB = function privateFuncB(test) {
   return test === privateMember;
  },

  privateFuncC = function privateFuncC(test) {
   if (privateFuncB(test)) {
    return 'test passed';
   } else {
    return 'test failed';
   }
  };

  return {
   publicFuncA: privateFuncA,
   privateFuncC: privateFuncC
  };
 }();

 module.exports = Utils;
}());
Then in another file you can load the module using require command like this:
var Utils = require('./Utils.js');
console.log(Utils.publicFuncA());
Notice that we wrote the full path of our module file. This can be avoided by packing the module and creating package.json.

You can load other packages within your definition - all of them will be loaded once needed. Remember that Node.js loads modules synchronously, so if your module requires prolonged initialization running during the require call, make sure to preload it before you use it. Also in Node.js, the module location is the namespace, so there's no need to namespace in the code as you've described.

AMD


AMD has separated itself from CommonJS production group, as it failed to reach an agreement in discussions with about using JavaScript module in an asynchronous situation. CommonJS created JavaScript as part of an effort to retrieve it outside of browsers; thus, could not generate agreement with AMD, which was focused on operation within browsers. According to Require.js site, which is the leading AMD implementation:

It is an improvement over CommonJS modules because:
  • It works better in the browser, it has the least amount of gotchas. Other approaches have problems with debugging, cross-domain/CDN usage, file:// usage and the need for server-specific tooling.
  • Defines a way to include multiple modules in one file. In CommonJS terms, the term for this is a "transport format", and that group has not agreed on a transport format.
  • Allows setting a function as the return value. This is really useful for constructor functions. In CommonJS this is more awkward, always having to set a property on the exports object. Node supports module.exports = function () {}, but that is not part of a CommonJS spec.

Definition


Since AMD focuses on asynchronous module loading, it urges you to list all the dependencies in the definition statement.
(function () {
 'use strict';
 
 define('Utils', ['jquery','underscore'], function($, _) {
  
  var privateMember = 1, 
  privateFuncA = function privateFuncA() {
   return 'privateFuncA';
  },
  
  privateFuncB = function privateFuncB(test) {
   return test === privateMember;
  },
  
  privateFuncC = function privateFuncC(test) {
   if (privateFuncB(test)) {
    return 'test passed';
   } else {
    return 'test failed';
   }
  };

  return {
   publicFuncA: privateFuncA,
   privateFuncC: privateFuncC
  };
 });
}());
Here we defined the Utils module, which depends upon JQuery and Underscore modules. If your module doesn't have any dependencies, you may omit the second parameter. You may also omit the first parameter, the name, which will make the module even more portable. It allows a developer to place the module in a different path to give it a different ID/name. The AMD loader will give the module an ID based on how it is referenced by other scripts.

Firstly we need to configure our starting point. Notice that our main script was placed in data-main attribute and not as a source. This way we load Require.js first and it will take care of loading our main script.
<script data-main="src/main.js" src="src/require.js"></script>
Then inside our main, we configure where each package resides. This way Require.js will know where to look for definitions of Underscore, jQuery and eventually Utils. We do this with help of requirejs.config method.
require.config({
    baseUrl: 'js/lib',
    paths: {
        jquery: 'jquery-1.9.0'
    }
});
The left side is the module ID and the right side is the path to the jQuery file, relative to baseUrl. Also, the path should NOT include the '.js' file extension.This example is using jQuery 1.9.0 located at js/lib/jquery-1.9.0.js, relative to the HTML page.

Non AMD libraries

You can also configure the dependencies, exports, and custom initialization for older, traditional "browser globals" scripts that do not use define() to declare the dependencies and set a module value. You do this with shim method. You can see the example of it's usage on Require.js site in the shim section.

Universal module


Someday you will want to create a module, which is both accessible in browser and server side environments. Require.js supports server side loading, providing CommonJS wrapper, however I wouldn't suggest you to follow this slippery road. Since nearly all Node.js developers don't use Require.js, they won't be able to use your beautiful module. However if you don't care about publicity and won't be sharing your work, you may try to unify your module creating and go only with Require.js.

If you'd like to make your module accessible from both Require.js and Node.js using CommonJS syntax, here is how you can do it:
(function () {
    'use strict';

 var Utils = function () {
  .....
 }();

 if (typeof define === 'function' && define.amd) {
     // Publish as AMD module
     define(function() {return Utils;});
 } else if (typeof(module) != 'undefined' && module.exports) {
     // Publish as node.js module
  module.exports = Utils;
 } else {
  // Publish as global (in browsers)
  window.Utils = Utils;
 }
}());
Basically we check for appropriate methods and act accordingly.
Sunday, April 20, 2014

Object Oriented JavaScript


The JavaScript language is simple and straightforward and often there’s no special syntax for features you may be used to in other languages, such as namespaces, modules, packages, private properties, and static members. For this reason, a lot of ambiguity lingers thought the streets of JavaScriptville.

Namespaces


Before we start creating classes, I would like to introduce the concept of namespaces. Namespaces help reduce the number of globals required by our programs and at the same time also help avoid naming collisions or excessive name prefixing. JavaScript doesn’t have namespaces built into the language syntax, but this is a feature that is quite easy to achieve. We'll create a global function, which will create a namespace according to the received fully qualified namespace name (e.g. JsDeepDive.Common.Managers). We'll iterate over each segment of the namespace and create namespaces where are needed. Full implementation looks like this:
function namespace(namespace) {
    "use strict";
    var object = window, tokens = namespace.split("."), token;

    while (tokens.length > 0) {
        token = tokens.shift();
        if (typeof object[token] === "undefined") {
            object[token] = {};
        }
        object = object[token];
    }
    return object;
}
Using this method is easy. The following code will create namespaces JsDeepDive.Common.Managers and JsDeepDive.DAL. The first line ensures to create our parent namespace, if it hasn't been created by previous modules.
var JsDeepDive = JsDeepDive || {};
namespace('JsDeepDive.Common.Managers');
namespace('JsDeepDive.DAL');

Static Classes


Now that we know how to create namespaces, let's see how to create static class. Logger, utils, factory pattern are usually implemented as static classes, which are easily created using Revealing Module Pattern. If you'd like to grasp a deeper knowledge about the pattern, have a look at Carl's Danley article.
var JsDeepDive = JsDeepDive || {};
namespace('JsDeepDive.Common');

JsDeepDive.Common.Utils = function () {
 "use strict";

 var privateMember = 1, 
 privateFuncA = function privateFuncA() {
  return 'privateFuncA';
 },
 
 privateFuncB = function privateFuncB(test) {
  return test === privateMember;
 },
 
 privateFuncC = function privateFuncC(test) {
  if (privateFuncB(test)) {
   return 'test passed';
  } else {
   return 'test failed';
  }
 };

    return {
        publicFuncA: privateFuncA,
        privateFuncC: privateFuncC
    };
}();
Here we created namespace JsDeepDive.Common and wrote a new static class, called Utils. In it we created 3 private methods and private member. Please notice how privateFuncB uses the member and the method itself is called from privateFuncC. In the bottom of class declaration we expose privateFuncA through publicFuncA and privateFuncC with the same name. Both privateFuncB and privateMember remain unreachable from outside the class.

Let's check our class and call its members:
var Utils = JsDeepDive.Common.Utils, c = console;
c.log('Utils.publicFuncA returned: ' + Utils.publicFuncA());
c.log('Utils.privateFuncA is ' + typeof Utils.privateFuncA);
c.log('Utils.privateMember is ' + typeof Utils.privateMember);
c.log('Utils.publicFuncA returned: ' + Utils.privateFuncC(1));
The output of out tests will be:
Utils.publicFuncA returned: privateFuncA
Utils.privateFuncA is undefined
Utils.privateMember is undefined
Utils.publicFuncA returned: test passed

Instantiatable Classes


There are 2 main ways to create instantiatable classes in JavaScript. One is through public methods, the other is by using prototype attribute. You can see the syntax difference in the example below:
function ConstructorPublicMethods() {
 var privateMember = 1;
 
 this.publicMethod1 = function publicMethod1(n) {
  return 2 * n;
 };
  
 this.publicMethod2 = function publicMethod2(n) {
  return 3 * n;
 };
}
  
function PrototypePublicMethods() {
 var privateMember = 1;
}
  
PrototypePublicMethods.prototype = {
 publicMethod1: function publicMethod1(n) {
  return 2 * n;
 },
  
 publicMethod2: function publicMethod2(n) {
  return 3 * n;
 }
};  
Here we created 2 classes using different methods. So which method is better? The prototype one and the reason is performance. The prototype assignment is much faster than merely creating public function using assignment operator. To be specific 99% percent slower and you can read all about it here. So why is there so much confusion you may ask? The problem with prototype method is inability to access private members from the public methods. Have a look at privateMember and let's try to access it from publicMethod2 using both methods by rewriting the method.
function publicMethod2(n) {
 var c = console;
 c.log('privateMember: ' + typeof privateMember);
 c.log('this.privateMember: ' + typeof this.privateMember);
 return 3 * n;
}

/* testing the method */
console.log('testing PrototypePublicMethods');
var obj = new PrototypePublicMethods();
obj.publicMethod2(2);

console.log('testing ConstructorPublicMethods');
obj = new ConstructorPublicMethods();
obj.publicMethod2(2);
Running the tests will prove the hypothesis and show that privateMember is undefined:
testing PrototypePublicMethods
privateMember: undefined
this.privateMember: undefined
testing ConstructorPublicMethods
privateMember: number
this.privateMember: undefined
So how can we use prototype method and still being able to access the private members? The trick is to expose a method using the public method way, but to limit it's accessibility to the outsiders. The exposed method will have the access to all the private members as desired and calling it from the prototype exposed methods will provide them the new ability. Little confused? Let me show the example presenting the case.
var JsDeepDive = JsDeepDive || {};
namespace('JsDeepDive.Common');

(function (key) {
    "use strict";
    JsDeepDive.Common.Manager = function () {
        /* Start private parameters and functions of the class */
        var privates = {
   privateMember: undefined, 
   
   privateFuncA: function privateFuncA() {
    return 'privateFuncA';
   },   
   
   privateFuncB: function privateFuncB(test) {
    return test === this.privateMember;
   },
   
   privateFuncC: function privateFuncC(test) {
    if (this.privateFuncB(test)) {
     return 'test passed';
    } else {
     return 'test failed';
    }
   },    
   
   _constructor: function _constructor() {
    console.log('_constructor is called');
    this.privateMember = 1;
   }
  };
        /* End private parameters and functions of the class */
  
  this._ = function (aKey) {
            return key === aKey && privates;
        };
        privates._constructor();        
    };

    JsDeepDive.Common.Manager.prototype = {
        publicFuncA: function publicFuncA() {
   return this._(key).privateFuncA();
  },
  
  privateFuncC: function privateFuncC(test) {
   return this._(key).privateFuncC(test);
  }
    };
}({}));
As you can see all the private methods are encapsulated within the privates member. Only methods defined within the class's scope can access them, specifically our tunnel method _, defined in line 34. This is a public method and can be accessed by anyone, but only the ones who know the secret key, can get the privates collection; others will always receive null. Please notice that we initiated the key with empty anonymous object - {}. This way no one will never be able to get the correct key. The strict equal operator, which is used while comparing the keys, ensures that no matter what we put in the aKey parameter, key === aKey is true only for the same object.

Static Methods


Once we can create static and instantiatable classes, creating static methods is a trifle. All methods of static classes are static as well, so this does it. When it comes to instantiatable classes, you may simple assign the method to the class name and add the implementation. Following the preceding example, the described can be achieved as following:
JsDeepDive.Common.Manager.staticMethodA = 
function staticMethodA() {
  return 'this is static method';
 };

/// somewhere in the code
console.log('staticMethodA: ' 
+ JsDeepDive.Common.Manager.staticMethodA());
Which will print:
staticMethodA: this is static method 
Hope you enjoyed the article and feel free to leave your comments below.
Sunday, April 13, 2014

What Is Bower And Why You Need It


So you've heard everyone talking about this mythical creature called Bower. But what exactly is it? Better to see once than to hear 100 times, so before we proceed any further take a peek at their site.


The problem


Recall how you used to manage, and maybe still do, your 3rd party libraries. Firstly you went to their official site or maybe github repository. After finding the latest minified version, you would get something like this - xxx-1.0.1.min.js, then downloaded and saved it into your project. At last referencing it in the HTML would do the trick by copy pasting the script tag - <script src="//code.jquery.com/jquery-1.11.0.min.js">.

But what would have happened if a new version came up? Well, if you were aware of the update, you would repeat the process again and put xxx-1.0.2.min.js in your library folder. Then you would change the reference in your HTMLs or JavaScript files. You could of course rename the file to xxx.js and omitting the version and 'min' suffix, but then you'd need to enter the file itself to verify the version; that is if the version was written there of course.

All this should have been done just for one library, but you well know that today's applications depend upon dozens of 3rd libraries. Each of them has its own version and keeping track of their changes has become a tedious if not impossible task for a man who just wanted to use some cool library. This is where Bower comes to help.


The solution


Basically, Bower is a package manager of JavaScript libraries. It was designed specifically to maintain the front-end related libraries like JQuery, Underscore and so on. You can use Bower to download libraries from the command line, without having to manually download each project from their respective sites. Bower keeps track of these packages in a manifest file called bower.json. Once you downloaded the package, the usage is up to you - Bower doesn't interfere nor assists with the loading process of the libraries.


The rumors


There is a lot of confusion among newcomers to the JavaScript package management world about the purpose of each tool and needs they come to solve. Let's talk about the most common rumors.

Bower vs npm


npm is most commonly used for managing Node.js modules, but some front-end libraries has crept into its repositories and may be downloaded from there as well.

Bower is created solely for the front-end and is optimized with that in mind. The biggest difference is that npm does nested dependency tree (size heavy) while Bower requires a flat dependency tree (puts the burden of dependency resolution on the user).

A nested dependency tree means that your dependencies can have its own dependencies which can have their own, and so on. This is really great on the server where you don't have to care much about space and latency. It lets you not have to care about dependency conflicts as all your dependencies use e.g. their own version of Underscore. This obviously doesn't work that well on the front-end.

Bower vs Requirejs


Bower is intended to keep track of the packages, whereas Requirejs for managing the dependencies inside the project. Once you've downloaded all the required libraries using the Bower, you would still need to reference all of them in your code in the right order. This is what Requirejs does.

The usage


Let us see how to install and use the Bower. In order to install it, just get it from the npm using the following code:

npm install -g bower

If you don't know what npm is or don't have one installed on your machine, please read the JavaScript developer toolkit article. Go to the project's folder and initiate the bower configuration file. The tool will ask you couple of question like naming and versions before it starts. To do this, type the following:

bower init

Once everything is set up, start downloading packages by typing their name:

bower install jquery

or typing the github repository directly:

bower install https://github.com/jquery/jquery

Bower supports many options to make your life easier like downloading specific version or auto-update all or some packages at once. All these can be read about on their site.