Tuesday, November 9, 2010

Javascript Design Patterns - Chaining

Chaining is really just a syntax hack. It allows you to express complex operations in a small amount of code by reusing an initial operation.

Chaining requires two parts:
- a factory (factory pattern) that creates an object around an HTML element,
- and methods that perform some action using that HTML element.

Strucure of a Chain

Here is the dollar function, which usually returns an HTML element or a collection of HTML elements as shown here:
function $() { 
var elements = []; for (var i = 0, len = arguments.length; i < len; ++i) {
}
var element = arguments[i]; if (typeof element === 'string') {
element = document.getElementById(element);
} if (arguments.length === 1) {
return element; elements.push(element);
}
} return elements;
Basically, you modify function to act as a constructor, store the elements as an array in an instance property, then return a reference to the instance in all prototype methods, you can give it the ability to chain. Building it: You modify the dollar function so it becomes a factory method, creating an object that will support chaining. Here is modified code:
(function() { 
// Use a private class. 
function _$(els) {
  this.elements = []; 
    for (var i = 0, len = els.length; i < len; ++i) {
      var element = els[i]; 
      if(typeof element === 'string') {
          element = document.getElementById(element); 
       }
      this.elements.push(element);
     }
}
 


 // The public interface remains the same. 
 window.$ = function() {
   return new _$(arguments); 
 };

})();

Since all objects inherit from their prototype, you can take advantage of the reference to the instance object being returned and run each of the methods attached to the prototype as a chain. Here is the code:
(function() { 
// Use a private class. 
function _$(els) {
  this.elements = []; 
    for (var i = 0, len = els.length; i < len; ++i) {
      var element = els[i]; 
      if(typeof element === 'string') {
          element = document.getElementById(element); 
       }
      this.elements.push(element);
     }
}
      //adding methods to private dollar constructor:
      _$.prototype = {
  each: function(fn){
   for(var i = 0, len = this.elements.length; i < len; ++i) {
    fn.call(this, this.elements[i]);
   }
   return this;
  },
  setStyle: function(prop, val) {
   this.each(function(){
    el.style[prop] = val;
   });
  return this;
  },
  show: function() {
   var that = this;
   this.each(function(el) {
    that.setStyle('display', 'block');  
   });
   return this;
  },
  addEvent: function(type, fn) {
   var add = function(el) {
   
     if(window.addEventListener) {
      el.addEventListener(type, fn, false);
     }else if(window.attachEvent) {
      el.attachEvent('on' + type, fn);
     }
    };
   this.each(function(el){
    add(el);
   }); 
   return this;
  }
 };

 // The public interface remains the same. 
 window.$ = function() {
   return new _$(arguments); 
 };

})();

Now you can write code like this:
$(window).addEvent('load', function() {
      $('test-1', 'test-2').show().
              setStyle('color', 'red').
              addEvent('click', function(e) {
              $(this).setStyle('color', 'green');
               });
  });

Using Callbacks to Retrieve Data from Chained Methods
For mutator methods, they're just fine, but with accessor methods, you may wish to return the data that you are requesting, instead of returning this. You can work around this problem by using function callbacks to return your accessed data. Here is simple example:
//Accessor with function callbacks. 
  window.API2 = window.API2 || {}; 
 API2.prototype = (function() {
   var name = 'Hello world'; 
    // Privileged mutator method. 
  setName: function(newName) {
     name = newName;
     return this; 
  },
     // Privileged accessor method. 
  getName: function(callback) {
      callback.call(this, name); 
      return this;
  } 
})();


       //Implementation code. 
    var o2 = new API2; 
    o2.getName(console.log).setName('Meow').getName(console.log); 
       //Displays 'Hello world' and then 'Meow'.

Summary
JavaScript passes all objects by reference, so you can pass these references back in every method. By returning this at the end of each method, you can create a class that is chainable.

This style helps to streamline code authoring and to a certain degree, make your code more elegant and easier to read.
Often you can avoid situations where objects are declared several times and instead use a chain.

If you want consistent interfaces for your classes, and you want both mutator and accessor methods to be chainable, you can use function callbacks for your accessors.

Javascript Design Patterns - Singleton Pattern - Branching

Branching is a technique that allows you to encapsulate browser differences into dynamic methods that get set at run-time.

If branching isn’t used, each time this method is called, all of the browser sniffing code must be run again. This can be very inefficient if the method is called often.

A more efficient way is to assign the browser-specific code only once, when the script loads.

That way, once the initialization is complete, each browser only executes the code specific to its implementation of JavaScript.

The ability to dynamically assign code to a function at run- time is one of the reasons that JavaScript is such a flexible and expressive language.

This kind of optimization is easy to understand and makes each of these function calls more efficient.

Branching isn’t always more efficient.
The next example shows a case when branching should be used, as the branch objects are small and the cost of deciding which to use is large.

Example: Creating XHR Objects with Branching

(There is a more advanced version of this in example for factory pattern.)

First determine how many branches you need. Since there are three different types of objects that can be instantiated, you need three branches.

Name each branch by the type of XHR object that it returns:

/* SimpleXhrFactory singleton, step 1. */ 

   var SimpleXhrFactory = (function() {
       // The three branches. 
         var standard = {
           createXhrObject: function() { 
                 return new XMLHttpRequest();
           } };
           var activeXNew = { 
               createXhrObject: function() {
                  return new ActiveXObject('Msxml2.XMLHTTP');
               }

             }; 
            var activeXOld = {
                  createXhrObject: function() { 
                        return new ActiveXObject('Microsoft.XMLHTTP');
                  } 
             };
          })();

Each of the three branches contains an object literal with one method, createXhrObject.

This method simply returns a new object that can be used to make an asynchronous request.

The second part to creating a branching singleton is to use the condition to assign one of these branches to the variable.

To do that, test each of the XHR objects until you find one that the given JavaScript environment supports:

/* SimpleXhrFactory singleton, step 2. */ 

     var SimpleXhrFactory = (function() {
         // The three branches. 
         var standard = {
               createXhrObject: function() { 
                     return new XMLHttpRequest();
               } 
          };
          var activeXNew = { 
                   createXhrObject: function() {
                         return new ActiveXObject('Msxml2.XMLHTTP');
                   } 
          };
           var activeXOld = { 
                  createXhrObject: function() {
                         return new ActiveXObject('Microsoft.XMLHTTP');
                  } 
           };
     
            // To assign the branch, try each method; return whatever doesn't fail. 
               var testObject; 
                try {
                       testObject = standard.createXhrObject(); 
                        return standard; 
                     // Return this if no error was thrown.
                } catch(e) {
                          try { 
                                testObject = activeXNew.createXhrObject(); 
                                return activeXNew; // Return this if no error was thrown.
                           } catch(e) {

                                try { 
                                    testObject = activeXOld.createXhrObject(); 
                                    return activeXOld; // Return this if no error was thrown.
                                } catch(e) {
                                    throw new Error('No XHR object found in this environment.');
                                }
                            }
                 } 
          })();

This singleton can now be used to instantiate an XHR object.

The programmer that uses this API need only call SimpleXhrFactory.createXhrObject() to get the correct object for the particular run-time environment.

Branching allows all of the feature sniffing code to be exe- cuted only once ever, instead of once for each object that is instantiated.

This is a powerful technique that can be used in any situation where the particular imple- mentation can only be chosen at run-time.

We cover this topic in more depth when we discuss the factory pattern.

Singleton Pattern Usage


When used for namespacing and modularizing your code, the singleton pattern should be used as often as possible.

It is one of the most useful patterns in JavaScript and has its place in almost every project, no matter how large or small.

In quick and simple projects, a singleton can be used simply as a namespace to contain all of your code under a single global variable.

On larger, more complex projects, it can be used to group related code together for easier maintainability later on, or to house data or code in a single well-known location.

In big or complicated projects, it can be used as an optimizing pattern: expensive and rarely used com- ponents can be put into a lazy loading singleton, while environment-specific code can be put into a branching singleton.


JavaScript’s flexibility allows a singleton to be used for many different tasks. We would even go as far as to call it a much more important pattern in this language than in any other. This is mostly because it can be used to create namespaces, reducing the number of global variables.

This is a very important thing in JavaScript, where global variables are more dangerous than in other languages; the fact that code from any number of sources and programmers is often combined in a single page means variables and functions can be very easily overwritten, effectively killing your code.

That a singleton can prevent this makes it a huge asset to any programmer’s toolbox.




Drawbacks of Singleton Pattern

By providing a single point of access, the singleton pattern has the potential to tightly couple modules together.

This is the main complaint leveraged at this pattern, and it is a valid one.
There are times when it is better to create an instantiable class, even if it is only ever instanti- ated once.

It also makes your code harder to unit test because it has the potential to tightly couple classes together.
You can’t independently test a class that calls methods from a single- ton; instead, you must test the class and the singleton together as one unit.

Singletons are best reserved for namespacing and for implementing branching methods.
In these cases, coupling isn’t as much of an issue.


There are times when a more advanced pattern is better suited to the task.

A virtual proxy can be used instead of a lazy loading singleton when you want a little more control over how the class gets instantiated.
A true object factory can be used instead of a branching singleton (although that factory may also be a singleton).

Don’t be afraid to investigate the more specific patterns in this book, and don’t settle on using a singleton just because it is “good enough.”
Make sure that the pattern you choose is right for the job.


Summary

Creating reusable and modular code.

Finding ways to organize and document that code is one of the biggest steps toward accomplishing that goal.

Singletons can help out enormously in that regard.

By putting your code within a singleton, you are going a long way toward creating an API that can be used by others without fear of having their global variables overwritten.

It is the first step to becoming an advanced and responsible JavaScript programmer.

JavaScript Design Patterns - Singleton Pattern - Lazy Instantiation

All of the implementations of the singleton pattern that we discussed so far share one thing in common: they are all created as soon as the script loads.

If you have a singleton that is expensive to configure, or resource-intensive, it might make more sense to defer instantiation until is needed.

Known as lazy loading, this technique is used most often for singletons that must load large amounts of data.

If you are using a singleton as namespace, a page wrapper, or as a way to group related utility methods, they probably should be instantiated immediately.

These lazy loading singletons differ in that they must be accessed through a static method. Instead of calling Singleton.methodName(), you would call Singleton.getInstance().methodName().

The getInstance method checks to see whether the singleton has been instantiated. If it hasn’t, it is instantiated and returned. If it has, a stored copy is returned instead.

To illustrate how to convert a singleton to a lazy loading singleton, let’s start with our skeleton for a singleton with true private members:

/* Singleton with Private Members, step 3. */
 MyNamespace.Singleton = (function() { 

 // Private members. var privateAttribute1 = false; var privateAttribute2 = [1, 2, 3];
     function privateMethod1() { 
         //…
     }    
     function privateMethod2(args) {
         //...
     }
     
     return { 
        // Public members. 
        publicAttribute1: true, 
        publicAttribute2: 10,

        publicMethod1: function() { 
              //...
        },

        publicMethod2: function(args) { 
               //...
        } 
      };
})();


So far, nothing has changed. The first step is to move all of the code within the singleton into a constructor method:

/* General skeleton for a lazy loading singleton, step 1. */ 

  MyNamespace.Singleton = (function() {
         
     function constructor() { 
        // All of the normal singleton code goes here. 
        
         // Private members. 
        var privateAttribute1 = false; 
        var privateAttribute2 = [1, 2, 3];

        function privateMethod1() { 
               //...
        } 
        function privateMethod2(args) {
                //...
        }

        return { 
              // Public members. 
              publicAttribute1: true, 
              publicAttribute2: 10,

              publicMethod1: function() { 
                     //...
              }, 
              publicMethod2: function(args) {
                       //…
              }

           }

      } //constructor 

})();


This method (constructor) is inaccessible from outside of the closure, which is a good thing.

You want to be in full control of when it gets called.
The public method getInstance is used to implement this control.

To make it publicly accessible, simply put it in an object literal and return it:

/* General skeleton for a lazy loading singleton, step 2. */ 
   MyNamespace.Singleton = (function() {
    
      function constructor() { 
            // All of the normal singleton code goes here. …
      }     
      return { getInstance: function() {
          // Control code goes here.
      } 
    })();



Now you are ready to write the code that controls when the class gets instantiated.
It needs to do two things:

- First, it must know whether the class has been instantiated before.
- Second, it needs to keep track of that instance so it can return it if it has been instantiated.

To do both of these things, use a private attribute and the existing private method constructor:

/* General skeleton for a lazy loading singleton, step 3. */ 
    MyNamespace.Singleton = (function() {
             
           var uniqueInstance; // Private attribute that holds the single instance.
           
           function constructor() { 
                  // All of the normal singleton code goes here. …
            }      
      
            return { 
               getInstance: function() {
                   if(!uniqueInstance) { // Instantiate only if the instance doesn't exist.                 
                        uniqueInstance = constructor();
                   } 
                 return uniqueInstance;
               }
            } 
})();


Once the singleton itself has been converted to a lazy loading singleton, you must also convert all calls made to it.

In this example, you would replace all method calls like this:
MyNamespace.Singleton.publicMethod1();

In their place, we would write method calls like this:
MyNamespace.Singleton.getInstance().publicMethod1();

Part of the downside of a lazy loading singleton is the added complexity.
The code used to create this type of singleton is unintuitive and can be difficult to understand (though good documentation can help).


If you need to create a singleton with deferred instantiation, it’s helpful to leave a comment stating why it was done, so that someone else doesn’t come along and simplify it to just a normal singleton.


It may also be useful to note that long namespaces can be shortened by creating an alias. An alias is nothing more than a variable that holds a reference to a particular object.

In this case, MyNamespace.Singleton could be shortened to MNS:
var MNS = MyNamespace.Singleton;

This creates another global variable, so it might be best to declare it within a page wrapper singleton instead.

When singletons are wrapped in singletons, issues of scope start to arise.
This would be a good place to use fully qualified names (such as GiantCorp.SingletonName) instead of this when accessing other members.

To be Continued: Branching

Tuesday, November 2, 2010

Javascript Design Patterns - Singleton Pattern

The singleton is one of the most basic, but useful, patterns in JavaScript, and one that you will probably use more than any other.

It provides a way to group code into a logical unit that can be accessed through a single variable.

By ensuring that there is only one copy of a singleton object, you know that all of your code makes use of the same global resource.

Singleton classes have many uses in JavaScript:

- They can be used for namespacing, which reduces the number of global variables in your pages.

- They can be used to encapsulate browser differences through a technique known as branching, which allows you to use common utility functions without worrying about browser sniffing.

- they can be used to organize your code in a consistent manner, which increases the readability and maintainability of your pages.

This pattern is extremely important in JavaScript, maybe more so than in any other language. Using global variables in your pages presents a huge risk, and a namespace created with a singleton is one of the best ways to remove those global variables.

The Basic Structure of the Singleton

It is essentially an object literal containing methods and attributes that have been grouped together because they are somehow related:

/* Basic Singleton. */
var Singleton = { 
    attribute1: true, 
    attribute2: 10,
   
    method1: function() {
    
    }, 
    method2: function(arg) {
    
    } 
 };

You should be aware that there is nothing in the language to prevent object modification from happening. If you do need to protect certain variables, you can always define them within a closure, as discussed in Encapsulation post (book reference Chapter 3).


Namespacing

A singleton object consists of two parts: the object itself, containing the members (both methods and attributes) within it, and the variable used to access it.
The variable is usually global, so that the singleton object can be accessed anywhere in the page. This is a key feature of the singleton pattern.

Namespacing is a large part of responsible programming in Javascript. Because everything can be overwritten, it is very easy to wipe out a variable, a function, or even a complete class without even knowing it.

These types of errors are extremely time-consuming to find.

In a lot of pages today, there is code from more than one source. There may be library code, advertiser code, and badge code in addition to anything you write. All of these variables exist within the global namespace of the page. In order to prevent collisions, you can put "all" of your code under a single variable. You can then group all of your code and data within objects or singletons under that single global variable.

Singleton with Private Members

- Using the Underscore Notation

- Using Closures

---------

Singleton As an Object Literal:
MyNamespace.Singleton = {};

/* Singleton with Private Members, step 1. */
MyNamespace.Singleton = function() { 
   return {};
}();


Some programmers find it useful to add another pair of parentheses around the function to denote that it is being executed as soon as it is declared. This is especially useful if the singleton is large. You can see at a glance that the function is used only to create a closure.
/* Singleton with Private Members, step 1. */
MyNamespace.Singleton = (function() { 
  return {};
})();


You can add public members to that singleton in the same manner as before by adding them to the object literal that gets returned:
/* Singleton with Private Members, step 2. */
MyNamespace.Singleton = (function() { 
   return { // Public members.
      publicAttribute1: true, 
      publicAttribute2: 10,

      publicMethod1: function() { 
      //…
      },
      publicMethod2: function(args) { 
      //...
      } 
    };
})();

Important

So why bother adding a function wrapper if it produces the same object that you can create using nothing more than an object literal?

Because that function wrapper creates a closure to add true private members.

Any variable or function declared within the anonymous function (but not within the object literal) is accessible only to other functions declared within that same closure.

The closure is maintained even after the anonymous function has returned, so the functions and variables declared within it are always accessible within (and only within) the returned object.

Here is how to add private members to the anonymous function:

/* Singleton with Private Members, step 3. */
MyNamespace.Singleton = (function() { 
      // Private members. 
      var privateAttribute1 = false; 
      var privateAttribute2 = [1, 2, 3];
    function privateMethod1() { 
          //...
    } 
    function privateMethod2(args) {
          //...
    }
    
     return { 
         // Public members. 
         publicAttribute1: true, 
         publicAttribute2: 10,
      
         publicMethod1: function() { 
              //…
         }, 
         publicMethod2: function(args) {
              //...
         } 
     };
})();

This particular singleton pattern is also known as the module pattern, referring to the fact that it modularizes and namespaces a set of related methods and attributes.

Using this pattern, you get all of the advantage of true private members with one of the drawbacks because this is only instantiated once.
That is what makes the singleton pattern one of the most popular and widely used in JavaScript.

Lazy Instantiation

To be Continued...