GitHub LinkedIn RSS
Showing posts with label OOP. Show all posts
Showing posts with label OOP. Show all posts
Saturday, November 8, 2014

JavaScript Adapter Design Pattern


Today we'll continue the JavaScript Design Patterns series by discussing the Adapter Pattern. Adapters are added to existing code to reconcile two different interfaces. They allows programming components to work together that otherwise wouldn't because of mismatched interfaces.

Adapter may be also used to ease the use with the existing interface. If the existing code already has an interface that is doing a good job, there may be no need for an adapter. But if an interface is unintuitive or impractical for the task at hand, you can use an adapter to provide a cleaner or more option-rich interface. Let's see how it looks in the following illustration:


Here we depict the example of legacy IDataManager interface, which is deeply used within the system. With the introduction of Redis database into the system, we need an adapter to fill the gaps. Our Adapter class has to implement the getData method, to make it consistent with the system, calling in turn the scan method to iterate over data stored in the database.

The implementation will look something like this:
function RedisDataManager() {
    this.connect = function() {
        console.log('Connect to database');
    };

    this.scan = function() {
        return 'Data from database';
    };
}

function DataManager() {
    this.getData = function() {
        return 'Legacy data';
    }
}
  
function Adapter() {
    var redis = new RedisDataManager();
    redis.connect();
    
    this.getData = function() {
        return redis.scan();
    }
}

function Client(dataManager) {
    console.log(dataManager.getData());
}

var client = new Client(new Adapter());
As you can see our Client is oblivious about the IDataManager implementation, and using the Adapter Pattern, we connect the RedisDataManager to it.

Next time we'll continue our discussion about structural patterns by introducing Bridge Pattern, which is very much alike.
Tuesday, September 30, 2014

JavaScript Promise


Nothing weights lighter than a promise
This maybe true regarding to human promises, however in the programming domain, promises are always kept. Following this optimistic note, today we'll be talking about JavaScript promises.

Event Handling Problem


Let's see what promises are good for and their basic capabilities starting with a problem they come to solve. Events are great for things of a repetitive nature like keydown, mousemove etc. With those events you don't really care about what have happened before you attached the listener. On contrary calling services and processing their response is a completely different kind of beast. Have a look at the following function, which reads a json file and returns it's content or an error in case of something goes wrong.
function readJSON(filename, callback) {
 fs.readFile(filename, 'utf8', function (err, res) {
     if (err) {
      return callback(err);
     }
     try {
       res = JSON.parse(res);
     } catch (ex) {
       return callback(ex);
     }
     callback(null, res);
 });
}
As you can see there're a lot of checks for errors inside the callback, which if forgotten or written in an incorrect order may cause it's creator quite a headache. This is where promises shine. JavaScript promises are not just about aggregating callbacks, but actually they are mostly about having a few of the biggest benefits of synchronous functions in async code! Namely, function composition of chainable async invocations and error bubbling; for example if at some point of the async chain of invocation an exception is produced, then the exception bypasses all further invocations until a catch clause can handle it (otherwise we have an uncaught exception that breaks our web app).

What is Promise?


A Promise is an object that is used as a placeholder for the eventual results of a deferred (and possibly asynchronous) computation. A promise can always be situated in one of three different states:
  • pending - The initial state of a promise.
  • fulfilled - The state of a promise representing a successful operation.
  • rejected - The state of a promise representing a failed operation.
Once a promise is fulfilled or rejected, it can never change again. The promises ease significantly the understanding of the program flow and aid in avoiding common pitfalls like error handling. They provide a direct correspondence between synchronous and asynchronous functions. What does this mean? Well, there are two very important aspects of synchronous functions, such as returning values and throwing exceptions. Both of these are essentially about composition. The point of promises is to give us back functional composition and error bubbling in the async world. They do this by saying that your functions should return a promise, which can do one of two things:
  • Become fulfilled by a value
  • Become rejected with an exception

Cross Platform Support


Over the years developer community has sprung numerous implementations of Promises. The most notable are Q, When, WinJS and RSVP.js, however since our blog focuses on the latest developments in the JavaScript world, we'll be only covering newest Promise class introduced in EcmaScript 6. You can see the browsers' support for the feature here, and in case you wish of your program to work in other browsers, as usually you can use the polyfill.

EcmaScript 6 Promise


The Promise interface represents a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers to an asynchronous action's eventual success or failure. This lets asynchronous methods return values like synchronous methods: instead of the final value, the asynchronous method returns a promise of having a value at some point in the future. So let's see our previous example using promises.
function readJSONPromise(filename) {
    return new Promise(function (resolve, reject) {
        fs.readFile(filename, 'utf8', function (err, res) {
            if (err) {
                reject(err);
            } else {
                try {
                    res = JSON.parse(res);
                } catch (ex) {
                    reject(ex);
                    return;
                }
                resolve(res);
            }
        });
    });
}
Oddly it seems very similar. So what do we gain? The true power reveals itself when we try to chain the calls.
readJSONPromise('./example.json').then(function onReadFile(res) {
    return res;
}).then(function onProcessFile(response) {
    console.log('response: ' + JSON.stringify(response));
}).catch(function onError(error) {
    console.error('error: ' + error);
});
Once you return the object, you can pass it to other function for further processing. It allows us to apply the concern separation design in an easy and clean way. You can look at the full code in Git repository.
Wednesday, September 17, 2014

JavaScript Singleton Design Pattern


In the previous articles we discussed Factory, Builder and Prototype design pattern. Today it's time to draw a line under creational design patterns by talking about Singleton Pattern.

Even though it's the most well known design pattern among the developers, the thought of writing one in JavaScript, makes most developers tremble. Naturally there is no reason for that and in fact implementing it is not that big of a deal. But first, let's see how it looks in the following illustration:


Basically our singleton contains one instance of itself and returns only it. Client cannot create a new instance or get other instance then one proposed by singleton.

So how do we implement it? The same way, like in any other language - using static classes. To brush off the rust, please read Object Oriented JavaScript article.
var Singleton = (function () {
    var instance;
 
    function createInstance() {
        var object = new Object();
        return object;
    }
 
    return {
        getInstance: function () {
            if (!instance) {
                instance = createInstance();
            }
            return instance;
        }
    };
})();

var instance1 = Singleton.getInstance();
var instance2 = Singleton.getInstance();

console.log("Same instance? " + (instance1 === instance2));  
var instance3 = new Singleton();
In our example we get two instances and check if they are the same. They are! Later we try to create our own instance using new keyword, which of course fails.
Same instance? true
TypeError: object is not a function
Next time we'll talk about behavioral design patterns. Come prepared ;-)
Sunday, July 27, 2014

JavaScript Builder Design Pattern


Today I would like to continue the series about design patterns we started with Factory Patterns in JavaScript and talk about the Builder pattern. For some reason it's being left behind in any design pattern usage in JavaScript. Maybe it was correct in the front end domain, but surely not in Node.js.

Builder pattern separates the construction of a complex object from its representation so that the same construction process can create different representations. The Builder pattern is based on Directors and Builders. Any number of Builder classes can conform to an IBuilder interface, and they can be called by a director to produce a product according to specification. The builders supply parts that the Product objects accumulate until the director is finished with the job. I'll be using the example from the factory pattern article to emphasize the differences between the patterns. Consider the class diagram for the Builder pattern:


And the implementation:
function FastCPU() {
    this.performOperation = function() {
        console.log("Operation will perform quickly");
    }
}
function SlowCPU() {
    this.performOperation = function() {
        console.log("Operation will perform slowly");
    }
}
 
function ExpensiveMotherBoard() {
    this.storeData = function() {
        console.log("There is a lot of RAM to store the data");
    }
}
 
function CheapMotherBoard() {
    this.storeData = function() {
        console.log("Little RAM. Swap file is used");
    }
}
 
function HighBudgetMachineBuilder() {
    this.getCPU = function() { return new FastCPU(); }
    this.getMotherBoard = function() {
     return new ExpensiveMotherBoard();
    }
}
 
function LowBudgetMachineBuilder() {
    this.getCPU = function() { return new SlowCPU(); }
    this.getMotherBoard = function() {
     return new CheapMotherBoard();
    }
}

function Director() {
    this.assembleMachine = function(builder) {
        var cpu = builder.getCPU(), 
        board = builder.getMotherBoard();
        return {
            cpu: cpu,
            board: board,
            test: function test() {
                this.cpu.performOperation();
                this.board.storeData();
            }
        }
    }
}
 
var director = new Director(),
    highBuilder = new HighBudgetMachineBuilder(),
    lowBuilder = new LowBudgetMachineBuilder(),
    highMachine = director.assembleMachine(highBuilder);
    lowMachine = director.assembleMachine(lowBuilder);
highMachine.test();
lowMachine.test();
We've added the director which assembles the machine. The client on the other hand, is not aware of the process of assembling the machines. It only uses the Director's method to do so.

The Builder and Abstract Factory patterns are similar in that they both look at construction at an abstract level. However, the Builder pattern is concerned with how a single object is made upby the different factories, whereas the Abstract Factory pattern is concerned with what products are made. The Builder pattern abstracts the algorithm for construction by including the concept of a director. The director is responsible for itemizing the steps and calls on builders to fulfill them. Directors do not have to conform to an interface.
Sunday, June 29, 2014

JavaScript Factory Patterns


Since June has 5 Sundays in it, today I will write a bonus article :) Following our last week's article about Publish and Subscribe Pattern with Postal.js, I'd like to broaden the topic talking about design patterns. The design patterns from the Gang of Four book offer solutions to common problems related to the object-oriented software design. It has been in use for decades and implemented in all server side languages. It's time we use them with JavaScript and start to write some piece of decent code. I'll be writing a series of articles covering all of them. As in the book, we'll be starting with creational patterns and cover both Abstract Factory and Factory Method patterns.

Abstract classes and interfaces enforce consistent interfaces in derived classes. In JavaScript we must ensure this consistency ourselves by making sure that each 'concrete' object has the same interface definition (i.e. properties and methods) as the others.

Abstract Factory Pattern


The Abstract Factory Pattern provides an interface for creating specific factories of dependent objects without specifying their concrete class.  Have a look at the illustration, depicting the pattern using UML.


Observe how Client is only aware of IMotherBoard and ICPU interfaces. The concrete factory responsible for creating the instances implementing these interfaces is also unknown. In JavaScript we don't have interfaces, but it doesn't mean that we cannot use the design pattern. Behold:
function FastCPU() {
    this.performOperation = function() {
        console.log("Operation will perform quickly");
    }
}
function SlowCPU() {
    this.performOperation = function() {
        console.log("Operation will perform slowly");
    }
}

function ExpensiveMotherBoard() {
    this.storeData = function() {
        console.log("There is a lot of RAM to store the data");
    }
}

function CheapMotherBoard() {
    this.storeData = function() {
        console.log("Little RAM. Swap file is used");
    }
}

function HighBudgetMachine() {
    this.getCPU = function() { return new FastCPU(); }
    this.getMotherBoard = function() {
     return new ExpensiveMotherBoard();
    }
}

function LowBudgetMachine() {
    this.getCPU = function() { return new SlowCPU(); }
    this.getMotherBoard = function() {
     return new CheapMotherBoard();
    }
}
All our classes implement the appropriate "ghost" interfaces. Now let's build our client:
function Client() {
 this.assembleMachine = function(factory) {
  var cpu = factory.getCPU(), 
   board = factory.getMotherBoard();
  // test the machine
  cpu.performOperation();
  board.storeData();
 }
}

var client = new Client();
client.assembleMachine(new HighBudgetMachine());
The output of course will be:
Operation will perform quickly
There is a lot of RAM to store the data 

Factory Method Pattern


The Factory Method pattern is a way of creating objects, but letting subclasses decide exactly which class to instantiate. Various subclasses might implement the interface; the Factory Method instantiates the appropriate subclass based on information supplied by the client or extracted from the current state. Please review the illustration below and the involved entities. Here we have interface ISorter, which defines common behaviour of our implementing classes, BubbleSorter and MergeSorterClient uses our factory Creator, which instantiates appropriate class.


Now in JavaScript:
function BubbleSorter() {
   this.sort = function (arr) {
        return "product A";
    }
}

function MergeSorter() {
   this.sort = function (arr) {
        return "product B";
    }
}

function Creator() {
    this.create = function(num) {
        if (num % 2 === 0) {
            return new BubbleSorter();
        }
        return new MergeSorter();
    }
}

var i, product, c = new Creator();
for (i = 0; i < 2; i += 1) {
    sorter = c.create(i);
    console.log(sorter.sort([5,2,7,3]));
}
Which produces the results:
bubble sorted
merge sorted

Conslusion


In Abstract Factory pattern, client is unaware of the specific factory used to instantiate the needed class, where as in Factory Method, a known factory is used.

Next time we'll continue our discussion about JavaScript design patterns and will cover additional creational patterns.

Sunday, May 25, 2014

Getters and Setters in JavaScript


This is the fourth article in the series of Object Oriented Javascript. Following our discussion on inheritance and it's integration with modular design pattern, I'd like take a deeper look into encapsulation and usage of mutator methods. Getters and setters allow you to build useful shortcuts for accessing and mutating data within an object.

__defineGetter__ and __defineSetter__


If you had searched for the information over the internet, you would have probably encountered recommendations, mostly from Microsoft :), to use __defineGetter__ and __defineSetter__. You may have also found some hacks for IE7 and even IE6. Even from a look at them you can smell something fishy. JavaScript is not C and doesn't encourage usage of underscores. Your gut feeling is right.
This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.
For the aforesaid reasons, I'm not going even to discuss these methods. Trying to polyfill and redefine them will only make things worse and you should stop yourself before starting such madness.

Object.defineProperty


The method defines new or modifies existing properties directly on an object, returning the object. Besides defining property accessors, the method also allows to define some neat features like writable to make the property read only, enumerable to show the property during enumeration process over object's properties and others like defining default values and ability to delete the property. You can have a look a the whole list here. Let's have a look at how it's used. I'll be showing a simple scenario without the extra features.

(function () {
   'use strict';
   function Room() {
      var temperature = null;

      Object.defineProperty(this, "temperature", {
         get: function() {
            console.log("get!"); 
            return temperature; 
        },
        set: function(value) { 
            console.log("set!"); 
            temperature = value; 
        }
    });
  }
})();
Here we declared the temperature property along with it's accessors. Take a look at line 4 - it's important to define the property before calling Object.defineProperty, otherwise you'll get an error. Once we've defined it, let's try to use it - actually you won't notice any difference:
var r = new Room();   
r.temperature = 1;
console.log(r.temperature);
The output will be:
set!
get!
1 
You'll encounter into problems once run on IE8 (of course :). Even though it supports it, there is some bad blood between the two - it could only be used on DOM objects. There is a workaround though - Object.defineProperties. It offers the same functionality as Object.defineProperty, however it is not supported by IE8 at all. How does it solve our problems? We can define it's polyfill and get full featured support in all browsers.

get and set


As of ECMAScript 5, a new syntax was introduced to help with the mess and make things cleaner - get and set. Let's see our previous example using the new syntax:
function Room() {}

Room.prototype = {
   get temperature() {
      console.log("get!");
      return this._temperature;
  },
  set temperature(temp) {
      console.log("set!");
      this._temperature = temp;
  }

};
The code of course produces the same results. You may not notice, but pay attention to the access to private member _temperature in lines 6 and 10. The attribute is created implicitly for us by runtime engine.

The problem with last solution is that it cannot be mimicked on not supporting browsers. Instead you'll get a syntax error. This is something you should take with yourself if you're willing to take such risks.

The old way


If you really need the IE support and don't like the idea of Object.defineProperties, you can always go back to creating your accessors manually:
function Room() {
   this._temperature = null;
}

Room.prototype = {
   getTemperature: function() {
      console.log("get!");
      return this._temperature;
  },
  setTemperature: function(temp) {
      console.log("set!");
      this._temperature = temp;
  }
};
And surely change your usage habits:
var r = new Room();   
r.setTemperature(1);
console.log(r.getTemperature());
Hope the article sheds some light onto the dark bog of JavaScript accessors. Be glad to here some comments.
Sunday, May 18, 2014

Modular Design Patterns and Inheritance


Last week we talked about JavaScript inheritance and if you recall we had talked about modular design patterns in JavaScript just a month ago. I would also like to talk about how to connect both modules and class inheritance. We've already discussed that modules are classes. So if we can link classes by inheritance relationship, the logical half of our brain suggests that we should be able to link modules as well. The logic prevails - we can.

AMD and inheritance


I'll be using the classes we defined in the inheritance article, Mammal and Dog, and create modules from them. Let's start with our super class:
(function () {
    'use strict';
 
 define(function() {
  
  function Mammal() {
    this.age = 0;
    console.info("Mammal was born");
  }
   
  Mammal.prototype.grow = function() {
      this.age += 1;
      console.log("Mammal grows");
  };

  return Mammal;
 });
}());
Let's use it in our entry point JavaScript file. Just to remind you this file is declared in data-main attribute.
(function () {
    'use strict';
 require(["Mammal"],
     function(Mammal) {
         var m = new Mammal();
         m.grow();
     }
   );
})();
Now it's time to create our Dog module. Since it needs Mammal for the inheritance, we'll list it in our dependency list. The implementation remains the same.
(function () {
    'use strict';
 define(["Mammal"],
     function(Mammal) {
         function Dog(name) {
     this.name = name;
     Mammal.call(this);
   }

   Dog.prototype.grow=function(){ 
     this._super.grow.call(this);
     this.age =+ 1; 
     console.log('Dog grows');
   }
    
   Dog.prototype = Object.create(Mammal.prototype);
   Dog.prototype.constructor = Dog;
   Dog.prototype._super = Mammal.prototype;
     
   return Dog;
     });
})();
And of course update our main file to see if it works:
(function () {
    'use strict';
 require(["Mammal", "Dog"],
     function(Mammal, Dog) {
         var m = new Mammal(), d = new Dog('Rocky');
   m.grow();
   d.grow();
     }
   );
})();

CommonJS and inheritance


As you recall modules should be defined using the CommonJS syntax if you want to use them in Node.js.
(function () {
    'use strict';
 
 function Mammal() {
   this.age = 0;
   console.info("Mammal was born");
 }
  
 Mammal.prototype.grow = function() {
     this.age += 1;
     console.log("Mammal grows");
 };

 module.exports = Mammal;
}());

As you can see we removed define method call and replaced return with module.exports.
(function () {
    'use strict';
 
 var Mammal = require('Mammal');

    function Dog(name) {
   this.name = name;
   Mammal.call(this);
 }

 Dog.prototype.grow=function(){ 
   this._super.grow.call(this);
   this.age =+ 1; 
   console.log('Dog grows');
 }
  
 Dog.prototype = Object.create(Mammal.prototype);
 Dog.prototype.constructor = Dog;
 Dog.prototype._super = Mammal.prototype;

 module.exports = Dog;
})();
Here instead of listing the dependencies, we just require the Mammal class in our Dog definition.
Sunday, May 11, 2014

Object Oriented JavaScript - Inheritance


Up until now, we've talked about Object Oriented JavaScript programming. Creating classes though doesn't make you code truly object oriented. What you lack is polymorphism, which is achieved through inheritance.

JavaScript is a bit confusing for developers coming from Java or C++, as it's all dynamic, all runtime, and it has no classes at all. It's all just instances (objects). Even the "classes" we simulate are just a function object.

Prototype Chain


When it comes to inheritance, JavaScript only has one construct: objects. Each object has an internal link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype. null, by definition, has no prototype, and acts as the final link in this prototype chain.

Object.create


After being long advocated forEcmaScript 5 has standardized a new method called Object.create. To keep up with progress, I'll be presenting inheritance using only this method. For those who want to use it with incompatible browsers, you must add its polyfill.

As the name states, the method creates a new object with the specified prototype object and properties. To understand the meaning of this, let's take a look at example:
function Mammal() {
  this.age = 0;
  console.info("Mammal was born");
}

Mammal.prototype.grow = function() {
    this.age += 1;
    console.log("Mammal grows");
};

function Dog(name) {
  this.name = name;
  Mammal.call(this);
}

Dog.prototype = Object.create(Mammal.prototype);
Dog.prototype.constructor = Dog;
var m = new Mammal(), d = new Dog('Rocky');
m.grow();
d.grow();
At first we created our superclass, Mammal, with attribute age and method grow. After that we declared class Dog, with its constructor and additional attribute, name. The inheritance happens in line 16, where our creation method takes Mammal's prototype and creates a new object inherited from it. Assigning it to Dog's prototype attribute, closes the loop. Take a look at line 11, where Dog's constructor is declared. Inside we call our Mammal constructor, by using call method. Together with constructor substitution in line 17, we achieve a proper relationship of our constructors. Otherwise instances of Dog would have a constructor of Mammal and attribute name wouldn't be initiated. The output of the code, can be seen below:
Mammal was born
Mammal was born
Mammal grows
Mammal grows 
You can see that Mammal's constructor as well as it's method is called when using both Mammal and Dog instances. Now what if we wanted to override the grow method with our own? The following code does exactly this:
Dog.prototype.grow=function(){ 
 Mammal.prototype.grow.call(this);
 this.age =+ 1; 
 console.log('Dog grows');
}
Calling the previous sequence again will produce the wanted results. Now we can see that our new implementation of Dog.grow is called in addition or Mammal's one.
Mammal was born
Mammal was born
Mammal grows
Mammal grows
Dog grows 
Rather than having to know that Dog inherits from Mammal, and having to type in Mammal.prototype each time you wanted to call an ancestor method, wouldn't it be nice to have your own property of the Dog pointing to its ancestor class? Those familiar with other Object Oriented languages may be tempted to call this property super, however JavaScript reserves this word for future use. Instead, we'll call it _super. The code of course produces the same results, however in my opinion it's somehow cleaner.
Dog.prototype._super = Mammal.prototype;

Dog.prototype.grow=function(){ 
 this._super.grow.call(this);
 this.age =+ 1; 
 console.log('Dog grows');
}
Object.create can take additional parameter, properties, which aid us to define new properties following Object.defineProperty syntax to the newly created class. In our example we could add new properties to the Dog this way:
Dog.prototype = Object.create(Mammal.prototype {
 color: { writable: true,  configurable:true, value: 'brown' }
});
I find it distasteful as it breaks your class definition from your methods. It surely makes it more tedious to define your attributes. However if you like it and find it useful, you may use it as well.

Object.create vs new


Object.create is not a new operator and they are not fully interchangeable as some suggest and shouldn't be considered as such. First of all with Object.create you can create an object that doesn't inherit from anything, by passing null as a prototype parameter - Object.create(null). Setting prototype attribute with null, and instantiate a class using new operator, will create a class inherited from Object.prototype. Secondly the performance of Object.create is dreadful and should be only used for class definitions, leaving the creation process to the operator. The measurements results can be seen here.

What about multiple inheritance?


To answer in one sentence - you should avoid it. Take a look at any wide spread modern object oriented language like Java, Ruby, C# and PHP (5 of course :) - non of them allows multiple inheritance. It brings more problems than benefits and most of the times your need of multiple inheritance is a signal your object structure is somewhat incorrect. Follow the SOLID principles and you will be able to solve everything without needing to resort to such measures.

This is not only my unprofessional opinion looking for a way to shine, but also a point of view of one of the most notable man in the sphere - Bjarne Stroustrup.  Take a look at excerpt from an interview over C++ modern style:
People quite correctly say that you don't need multiple inheritance, because anything you can do with multiple inheritance you can also do with single inheritance. You just use the delegation trick I mentioned. Furthermore, you don't need any inheritance at all, because anything you do with single inheritance you can also do without inheritance by forwarding through a class. Actually, you don't need any classes either, because you can do it all with pointers and data structures. But why would you want to do that? When is it convenient to use the language facilities? When would you prefer a workaround? I've seen cases where multiple inheritance is useful, and I've even seen cases where quite complicated multiple inheritance is useful. Generally, I prefer to use the facilities offered by the language to doing workarounds.
But if you insist, it can be accomplished through inheritance by copying properties, also known as mixinsjQuery.extend is the most commonly used implementation.
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.