Lazy Loading

You may experience working with active record or other ORM that make you realise the its cool feature with Lazy loading. Lazy loading provides you a way to load the data or object and its related objects only at the time you need it. It would be very handy to load all the related objects at the first loading since some of the data or objects you don’t really need it anyway. for further reading please loot at http://martinfowler.com/eaaCatalog/lazyLoad.html. There are three ways to implement lazy loading.

1. Lazy Initialization

With lazy initialization, the object to be lazily loaded is originally set to null, and every request for the object checks for null and creates it “on the fly” before returning it first.

/**
 *	Implement lazy initialization for singleton
 */
var Singleton = function(){
	//Object first is set to null
	var _uniqueInstance = null;
	return {
		//return an uniqInstance
		getInstance: function(){
			if(_uniqueInstance == null) _uniqueInstance = new Singleton();
			return _uniqueInstance;
		}
	}
}

2. Virtual Proxy

A virtual proxy is an object that “looks like” the object that is to be lazily loaded. Both the object and the proxy implement the same interface, with the proxy providing a wrapper that instantiates and initializes the object when one of its properties is accessed for the first time.

3. Ghost

A ghost is the object that is to be loaded in a partial state. It may only contain the object’s identifier, but it loads its own data the first time one of its properties is accessed. This specific implementation of the Proxy Design Pattern is called a Ghost.

For the Ghost pattern, there is an object that mirrors the real object with it public methods. the mirror object act just a stub with calls to our lazy load operation. When the real object is actually used, we’ll load the real object, replacing the mirror with the real one. Then we can call the same method again and referencing the real object that loaded.

To see how  really ghost work, I will be using YUI loader to demonstrate. YUI’s Loader Utility require few thing to be done in sequence to make it work properly. First We need to add the module’s information to the loader; tell the loader we require it; and then assign the callback to the loader’s onSuccess handler. In YUI, calling loader.insert() starts the loader, creating script nodes for all required modules and then calling the onSuccess callback when those nodes have completed. reference from http://www.digital-web.com/articles/improve_page_performance_with_lazy_loading/

var HelloWorld = {
  is_loaded: false,
  lazyLoad: function(callback) {
    var loader = new YAHOO.util.YUILoader();
    loader.addModule({
      name: "helloworld",
      type: "js",
      fullpath: "yui_ex/helloworld.js"
    });
    loader.require("helloworld");
    if (callback) {
      loader.onSuccess = callback;
    }
    loader.insert();
  },
  sayIt: function() {
    var args = arguments;
    HelloWorld.lazyLoad(function() { HelloWorld.sayIt.apply(HelloWorld, args); });
  }
};

an other implementation of Virtual Proxy
//proxy name space
var Proxy = {};

//Real object, which normaly expesive or memory intensive to instantiate
Proxy.RealImage = function(fileName){
        var self = this;
        var _init = function(fileName){
	    self.fileName = fileName;
	    loadImageFromDisk();
        }
	
	//Private method, for loading operation
	var loadImageFromDisk = function(){
		alert('Loading ' + this.fileName);
	};
	
	this.displayImage = function(){
		alert('Displaying ' + this.fileName);
	};
        _init(fileName);
};

//Proxy object, which act as a ghost, it has reference to the real object
//When needed the real object is instantiated inside proxy
Proxy.ProxyImage = function(name){
	this.fileName = name;
	this.image;
	
	this.displayImage = function(){
		if(this.image == null) {
                    this.image = new Proxy.RealImage(this.fileName); //load only on demand
                }
                this.image.displayImage();
	};

};

//MyLab Area
var image1 = new Proxy.ProxyImage('MonkeyProgrammingJavascript');
var image2 = new Proxy.ProxyImage('MonkeySeeingProxy');
var image3 = new Proxy.ProxyImage('MokeySmile');

image1.displayImage(); //loading necessary
image2.displayImage(); //loading necessary
image1.displayImage(); //no loading, already loaded
Advertisements

Decorator Pattern

Definition

The Decorator Pattern is used for adding additional functionality to a particular object as opposed to a class of objects. It is easy to add functionality to an entire class of objects by subclassing an object, but it is impossible to extend a single object this way. With the Decorator Pattern, you can add functionality to a single object and leave others like it unmodified.

A Decorator, also known as a Wrapper, is an object that has an interface identical to an object that it contains. Any calls that the decorator gets, it relays to the object that it contains, and adds its own functionality along the way, either before or after the call. This gives you a lot of flexibility, since you can change what the decorator does at runtime, as opposed to having the change be static and determined at compile time by subclassing. Since a Decorator complies with the interface that the object that it contains, the Decorator is indistinguishable from the object that it contains.  That is, a Decorator is a concrete instance of the abstract class, and thus is indistinguishable from any other concrete instance, including other decorators.   This can be used to great advantage, as you can recursively nest decorators without any other objects being able to tell the difference, allowing a near infinite amount of customization.

decorator

Source Code

var Decorator = {};

//Decoratee
Decorator.Coffee = function(){
	this.getDescription = function(){
		return 'Coffee';
	};
	this.getCost = function(){
		return 2.5;
	};
};

//Decorator
Decorator.Milk = function(decoratee){
	var obj = decoratee;
	this.getDescription = function(){
		return obj.getDescription() + " With MilK";
	};
	this.getCost = function(){
		return obj.getCost() + 0.5;
	};
};

//Decorator
Decorator.Mocha = function(decoratee){
	var  obj = decoratee;
	this.getDescription = function(){
		return	obj.getDescription() + ' With Mocha';
	};
	this.getCost = function(){
		return obj.getCost() + 1.0;
	};
};

var coffee = new Decorator.Coffee();
//Add milk to coffee
var coffeeMilk = new Decorator.Milk(coffee);
//Add mocha
var coffeeMilkMocha = new Decorator.Mocha(coffeeMilk);

console.log(coffeeMilkMocha.getDescription());
console.log(coffeeMilkMocha.getCost())

Replace Nested Condition with Guard Cluase

I have found myself really good stuff, when I was reading the book called ‘Refactoring The Existing Code’ by Matin Fowler. I will just quote from his book and Hope you may find it useful.

A method has conditional behavior that does not make clear the normal path of execution.

Use guard clauses for all the special cases.

 double getPayAmount() {

    double result;

    if (_isDead) result = deadAmount();

    else {

        if (_isSeparated) result = separatedAmount();

        else {

            if (_isRetired) result = retiredAmount();

            else result = normalPayAmount();

        };

    }

  return result;

  };

And Here the refactored version with Guard Cluase

double getPayAmount() {

    if (_isDead) return deadAmount();

    if (_isSeparated) return separatedAmount();

    if (_isRetired) return retiredAmount();

    return normalPayAmount();

  };

Motivation

I often find that conditional expressions come in two forms. The first form is a check whether either course is part of the normal behavior. The second form is a situation in which one answer from the conditional indicates normal behavior and the other indicates an unusual condition.

These kinds of conditionals have different intentions, and these intentions should come through in the code. If both are part of normal behavior, use a condition with an if and an else leg. If the condition is an unusual condition, check the condition and return if the condition is true. This kind of check is often called a guard clause [Beck].

The key point about Replace Nested Conditional with Guard Clauses is one of emphasis. If you are using an if-then-else construct you are giving equal weight to the if leg and the else leg. This communicates to the reader that the legs are equally likely and important. Instead the guard clause says, “This is rare, and if it happens, do something and get out.”

I often find I use Replace Nested Conditional with Guard Clauses when I’m working with a programmer who has been taught to have only one entry point and one exit point from a method. One entry point is enforced by modern languages, and one exit point is really not a useful rule. Clarity is the key principle: if the method is clearer with one exit point, use one exit point; otherwise don’t.

Abstract Factory

Intent: A software design pattern, the Abstract Factory Pattern provides a way to encapsulate a group of individual factories that have a common theme. In normal usage, the client software would create a concrete implementation of the abstract factory and then use the generic interfaces to create the concrete objects that are part of the theme. The client does not know (or care) about which concrete objects it gets from each of these internal factories since it uses only the generic interfaces of their products. This pattern separates the details of implementation of a set of objects from its general usage.

abstractfactory
//Name Space
var AbstractFactory = {};
//Abstract Engine
AbstractFactory.FerrariEngine = function(){
	this.createEgnine = function(){
		console.log('Create egine for Ferrari Car');
	};
};
AbstractFactory.MercedesEngine = function(){
	this.createEgnine = function(){
		console.log('Create egine for Mercedes Car');
	};
};
AbstractFactory.ToyotaEngine = function(){
	this.createEgnine = function(){
		console.log('Create egine for Toyota Car');
	};
};

//Abstract Steering
AbstractFactory.FerrariSteering = function(){
	this.createSteering = function(){
		console.log('Create Steering for Ferrari Car');
	};
};
AbstractFactory.MercedesSteering = function(){
	this.createSteering = function(){
		console.log('Create Steering for Mercedes Car');
	};
};
AbstractFactory.ToyotaSteering = function(){
	this.createSteering = function(){
		console.log('Create Steering for Toyota Car');
	};
};

//Abstract Wheel
AbstractFactory.FerrariWheel = function(){
	this.createWheel = function(){
		console.log('Create Wheel for Ferrari Car');
	};
};
AbstractFactory.MercedesWheel = function(){
	this.createWheel = function(){
		console.log('Create Wheel for Mercedes Car');
	};
};
AbstractFactory.ToyotaWheel = function(){
	this.createWheel = function(){
		console.log('Create Wheel for Toyota Car');
	};
};

//AbstractFactory
AbstractFactory.FerrariFactory = function(){
	this.createEngine = function(){
		return new AbstractFactory.FerrariEngine();
	};
	this.createSteering = function(){
		return new AbstractFactory.FerrariSteering();
	};
	this.createWheel = function(){
		return new AbstractFactory.FerrariWheel();
	};
};

AbstractFactory.MercedesFactory = function(){
	this.createEngine = function(){
		return new AbstractFactory.MercedesEngine();
	};
	this.createSteering = function(){
		return new AbstractFactory.MercedesSteering();
	};
	this.createWheel = function(){
		return new AbstractFactory.MercedesWheel();
	};
};

AbstractFactory.ToyotaFactory = function(){
	this.createEngine = function(){
		return new AbstractFactory.ToyotaEngine();
	};
	this.createSteering = function(){
		return new AbstractFactory.ToyotaSteering();
	};
	this.createWheel = function(){
		return new AbstractFactory.ToyotaWheel();
	};
};

//Factory of Factory
AbstractFactory.FactoryOfFactory = function(factory){
	switch(factory){
		case 'ferrari':
			var obj = new AbstractFactory.FerrariFactory();
			return {'engine': obj.createEgnine(), 'steering': obj.createSteering(), 'wheel': obj.createWheel()}
		case 'mercedes':
			var obj = new AbstractFactory.MercedesFactory();
			return {'engine': obj.createEgnine(), 'steering': obj.createSteering(), 'wheel': obj.createWheel()}
		case 'toyota':
			var obj = new AbstractFactory.ToyotaFactory();
			return {'engine': obj.createEgnine(), 'steering': obj.createSteering(), 'wheel': obj.createWheel()}
	}
}

Facade Pattern

The Facade pattern is a software engineering design pattern commonly used with Object-oriented programming.

A facade is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can:

  • make a software library easier to use and understand, since the facade has convenient methods for common tasks;
  • make code that uses the library more readable, for the same reason;
  • reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system;
  • wrap a poorly-designed collection of APIs with a single well-designed API (as per task needs).

An Adapter is used when the wrapper must respect a particular interface and must support a polymorphic behavior. On the other hand, a facade is used when one wants an easier or simpler interface to work with.

Graph

facadedesignpattern

Implementaion

var Facade = {};

//Sub Systems
Facade.SubSystemA = function(){
	this.doSomeThing = function(){
		console.log("SubSystemA's method is called");
	};
};

Facade.SubSystemB = function(){
	this.saySomeThing = function(){
		console.log("SubSystemA's method is called");
	};
};

Facade.SubSystemC = function(){
	this.getSomeThing = function(){
		console.log("SubSystemA's method is called");
	};
};

Facade.SubSystemD = function(){
	this.playSomeThing = function(){
		console.log("SubSystemA's method is called");
	};
};

//Facade
Facade.SubSystemInterface = function(){
	var _subSystemA = new Facade.SubSystemA();
	var _subSystemB = new Facade.SubSystemB();
	var _subSystemC = new Facade.SubSystemC();
	var _subSystemD = new Facade.SubSystemD();

	this.playSomeThing = function(){
		_subSystemA.doSomeThing();
		_subSystemB.saySomeThing();
	};

	this.saySomeThing = function(){
		_subSystemC.getSomeThing();
		_subSystemD.playSomeThing();
	}
};

//Procedure
var facadeObj = new Facade.SubSystemInterface();
facadeObj.playSomeThing();
facadeObj.saySomeThing();