Showing posts with label design pattern. Show all posts
Showing posts with label design pattern. Show all posts

Sunday, February 7, 2016

Design Patterns : Facade Pattern

You may also like to see:

Facade design pattern is a structural design pattern. Word facade means 'a deceptive outward appearance'. As facade design pattern hides all the complexities of one or many sub-systems and provides a clean, easy to use facade interface.

We can create multiple Facade interfaces by grouping relevant sub-system in particular class. The client will communicate these facades instead of complex individual subsystems.

Facade Design Pattern - Class Diagram

Implementation

Let's implement a facade pattern on an e-commerce site. We are going to create an online shopping system in which user selects an item from a catalog and place an order. Let's see its code

public class Inventory 
{
    public bool IsItemAvailable(String itemId) 
    {
       return "Item details";
    }
}

public class Payment 
{
    public String Pay(String itemId,Paypal paypal)
    {
       return "Charge for items";
    }
}

public class Shipping 
{
    public String ShipOrder(String itemId,Address shipmentAddress) 
    {
       return "Ship items to address";
    }
}

public class OrderFacade 
{
    // composed of all Order related sub-systems
    Payment _Payment;
    Inventory _Inventory;
    Inventory _Shipping;

    public void OrderFacade()
    {
        _Payment = new Payment();
        _Inventory = new Inventory();
        _Shipping = new Shipping();
    }

    public void PlaceOrder(String itemId,string creditCard,string shipmentAddress) 
    {
      // check if item is available 
      if(!_Inventory.IsItemAvailable(itemId)) return "Item Not Available";
      // charge for item price
      _Payment.Pay(itemId, new Paypal(creditCard));
      // ship order to customer
      _Shipping.ShipOrder(itemId,shipmentAddress) 
    }
}

public class Client 
{
    public static void main()
    {
       OrderFacade orderFacade = new OrderFacade();
       orderFacade.PlaceOrder("1234", "321546", "23-B Frim Road, Moscow");         
    }
}


As you have seen OrderFacade has encapsulated all the order-related activities and now client just has single point to communicate instead of invoking each sub-system individually. OrderFacade will delegate relevant sub-system and will complete the client request.

Facade pattern provides an interface which is easy to use for a client by hiding many interfaces. This pattern is actually straightforward but it is quite powerful. It allows us to make our system loosely coupled. There is a design principle Least Knowledge which guide us to have fewer dependencies between objects which mean objects should not be tightly coupled otherwise it would be difficult to manage.

Using Facade pattern as we know we have an interface which is responsible for communicating between the objects so it actually allows us to have fewer dependencies within objects. It has many advantages for instance in our example of online shopping system if our payment system is completely independent we can easily change it anytime without affecting the client.

Conclusion


Facade design pattern is a structural pattern which makes design easy by allowing to make a system less tightly coupled and provide an interface to the client which is clean and easy to use by hiding all complexities of sub-systems.


You may also like to see:

Friday, February 5, 2016

Design Patterns : Adapter Pattern - Be Adaptive

You may also like to see:

Adapter pattern works as a bridge between two separate objects. It converts interface of a class into another interface which is required. Adapter pattern lets different classes work together that could not otherwise due to the different interface of each class.

Understanding Adapter pattern is not that difficult because it works same as we see an adapter in the real world. The simplest example is AC power adapter which we use for cell-phone, laptop chargers. Electricity at home socket is 220 volts (or 110 volts) but our cell phone needs 5-12 volts so we need an adapter which should convert the power to required range.

Adapter in Programming


Let's see a real world example for Adapter pattern. Information sharing system's team is working on a system which uses social networks sites to share the content. The team has designed an interface which is implemented by Facebook, Twitter, and Linkedin classes. The system is using this interface to switch between these sites and share the content. Developers have to spend a lot of time in implementing these network site's public APIs in these classes and make system bug free and tested.


Here is code implementation of the system.
public interface ISocialNetworks
{
    bool Login(string username, string password);
    bool Share(string content);
}

public class Facebook: ISocialNetworks
{    
    public bool Login(string username, string password)
    {
       //Login Using Facebook API
    }

    public bool Share(string content)
    {
       //Share Using Facebook API
    }
}

public class Twitter: ISocialNetworks
{    
    public bool Login(string username, string password)
    {
       //Login Using Twitter API
    }

    public bool Share(string content)
    {
       //Share Using Twitter API
    }
}

//similarly for Linkedin


Everything was working fine until client wanted Google+ also in the list and team know to implement the same interface you have to understand APIs and have to put a huge effort in implementations. But you found that Google+ has already developed a library so you downloaded that library and try to integrate into your system.


There is a little problem Google+ developers have implemented their own interface which is not compatible with our information sharing system. Here is the code:
public interface IGoogleSocialNetworks
{
    bool Authenticate(string username, string password);
    bool Post(string content);
}

public class GooglePlus: IGoogleSocialNetworks
{    
    public bool Authenticate(string username, string password)
    {
       //Login Using Google API
    }

    public bool Post(string content)
    {
       //Share Using Google API
    }
}


Now here comes the adapter which will convert interface of Google+ library to the interface of desired system interface i.e, ISocialNetworks. Let's see its code implementation
public class GoogleNetworksAdapter: ISocialNetworks
{
    GooglePlus GoogleLibrary;

    public void GoogleNetworksAdapter (GooglePlus googleLibrary)
    {
       this.GoogleLibrary = googleLibrary;
    }

    public bool Login(string username, string password)
    {
       GoogleLibrary.Authenticate(username, password);
    }

    public bool Share(string content)
    {
       GoogleLibrary.Post(content);
    }
}

Let see design diagram after implementing adapter pattern



Now since Google+ adapter has the same interface as our other Social Networks i.e, ISocialNetworks so it can be use in system easily. Here is how client uses the adapter:
  1. Client make a request to Adapter class (GoogleAdapter) for a method of target interface (ISocialNetworks) e.g, Login
  2. Adapter class translate that request to adapted object method (IGoogleSocialNetwoks) e,g, Authenticate and return response
  3. Client receive the response without realizing that Adapter converted its request to another form.

Here is the class diagram of Adapter Pattern


Adapter pattern uses other good practices of Object Oriented for example object composition in Adapter class to wrap adapted functionalities in target interface. Another advantage of using this object composition is that this adapter can be used with any child class that inherits this Adapted class.


Special Scenario

We have seen a simple example in which all the methods of target interface were available in adapted class. What if there is a method in target interface which is not available in adapted class? In that case adapter pattern is not perfect to use because we have to throw a NotImplementedException. So the client will have to watch out for possible exceptions from the adapter class. The Adapter class should be well documented to reduce the chance of leaving unhandled exception at the client end.


You may also like to see:

Saturday, January 30, 2016

Decorator Design Pattern - Decorating Objects

You may also like to see:

Decorator Pattern is a design Pattern that allows to dynamically add behavior to an existing individual object without making any code changes to the underlying classes. It is a flexible replacement to sub-classing for extending functionality to an object.

If you think inheritance is everything than decorator pattern helps you to learn the power of extension at run-time instead of compile-time. Let's try to learn and implement decorator pattern on a problem.


Decorator Pattern in Pizza Corner Problem

Pizza Corner growing restaurant chain around. Because they have grown, they’re trying to update their ordering systems to match their Pizza offerings. While starting their business they created their classes like this.

Pizza Corner order system classes
Pizza Corner order system's classes design

Other than regular Pizza, you can ask for several pizza topping options like Bacon, Black olives, Chicken, Extra cheese, Mushrooms, Onions, Sausage and much more. Pizza Corner charges for each of these topping, so they want to add these into their system.


First Implementation

First implementation of adding new abilities in system team created a child class for each pizza with each topping option. So first implementation looks like.

If your first thought was also to use inheritance for this problem then you are incorrect. What if Pizza Corner started offering more toppings or added new pizza type you have to add all combination of classes in a system which will become hard to manage.

Alternate Solution

Developer team realize that this subclassed solution is not going to work and its actually a bad design so they started redesigning the system. Now they created instance variables for each topping option in the base class. So each child class can set options which it required.

Pizza Corner System with Instance variable

This solution reduced the size of classes but there is another problem if you have noticed now all the classes has all the topping options so Vegie can also have chicken topping which should not be allowed. Additionally, this design also violate the basic design principle of "Classes should be open
for an extension, but closed for modification." As whenever a new topping option will be introduced we need to modify our base class which is not correct.

Decorator Pattern


As we have seen different approaches for our problem at Pizza Corner which have not work out very well. Let's implement Decorator Pattern in this problem.


For decorator pattern we take our pizza type object and than decorate it with different toppings. Lets say we got an order for BBQChicken with Onions, ExtraCheese and Mushrooms.

  1. First take a BBQChicken object
  2. Decorate it with Onions
  3. Decorate it with ExtraCheese
  4. Decorate it with Mushrooms
  5. Call the cost() method and delegation will add cost of all topping and pizza

Pizza Corner System - Decorator Pattern
Decorator Pattern - Decorating Objects

Here are some key points for decorator pattern implementations:


  • Decorators object should have the same base type as the objects they are decorating.
  • We can use more than one decorators to wrap an object.
  • Given that the decorator has the same supertype as the object it decorates, we can pass around a decorated object in place of the original (wrapped) object.
  • The decorator object apply its own behavior either after or/and before delegating to the object it decorates.
  • We can decorate objects dynamically at runtime with as many decorator as we required.

Code Implementation

Here is a diagram which shows the design of decorator pattern. We have to implement this design for our system. I am going to implement it in C# language.

Decorator Pattern
Decorator Pattern - Image from Head First Design Pattern

Our base class of Pizza which will be inherited by all pizza types and toppings.

public abstract class Pizza 
{
  String description = “Unknown Pizza”;
  public String getDescription() 
  {
    return description;
  }

  public abstract double cost();
}

Here are our concrete components classes for each pizza type. Each concrete components will set is own definition for cost method and set description.

public class BBQChicken : Pizza
{
  public BBQChicken() 
  {
    description = “BBQ Chicken”; 
  }
  public double cost() 
  {
    return 800; //rupees
  }
}

public class HotChickenWings: Pizza
{
  public HotChickenWings () 
  {
    description = “Hot Chicken Wings”;
  }
  public double cost() 
  {
    return 750; //rupees
  }
}
public class Vegie : Pizza
{
  public Vegie() 
  {
    description = “Vegetable Pizza”; 
  }
  public double cost() 
  {
    return 650; //rupees
  }
}

Let implement topping decorator abstract class:

public abstract class ToppingDecorator : Pizza 
{
  public abstract String getDescription();
}

We have implemented our base topping decorator class, lets implement decorator class.

public class Onions : ToppingDecorator // ToppingDecorator inherit Pizza 
{
  Pizza pizza;
  public Onions(Pizza pizza) 
  {
    this.pizza = pizza;
  }
  public String getDescription() 
  {
    return pizza.getDescription() + “, Onions”;
  }
  public double cost() 
  {
    return 120 + pizza.cost();
  }
}
public class ExtraCheese : ToppingDecorator // ToppingDecorator inherit Pizza 
{
  Pizza pizza;
  public ExtraCheese(Pizza pizza) 
  {
    this.pizza = pizza;
  }
  public String getDescription() 
  {
    return pizza.getDescription() + “, ExtraCheese”;
  }
  public double cost() 
  {
    return 160 + pizza.cost();  
  }
}
// similarly implement all toppings

Serve Some Pizzas


As we have implemented decorator pattern for Pizza Corner lets serve some order of pizza and see how its going to work.

public class PizzaCorner
{
  public static void Main(String[] args)
  {

    Pizza pizza = new HotChickenWings();
    System.Console.WriteLine(pizza.getDescription() + “ Rs.” +pizza.cost());

    Pizza pizza2 = new BBQChicken();
    pizza2 = new Onions(pizza2);
    pizza2 = new ExtraCheese(pizza2);
    pizza2= new Mushrooms(pizza2);
    // cost triggering order is Mushrooms, ExtraCheese, Onions, BBQChicken
    System.Console.WriteLine(pizza2.getDescription()+ “ Rs” +pizza2.cost());
  }
}

Decorator Pattern in JavaScript

Let's implement the decorator pattern in JavaScript. Let's say a Cell Phone company implementing their system. They create Cell Phone with different features e.g, Camera, Wifi, 3G, Bluetooth etc each of these features has some cost. They want to implement their system in a way they don't need to change the whole system when they introduce a new phone model with some feature. Here we going to use decorator pattern in which we take base Cell Phone object and decorate it with Feature decorator.

//object we're going to decorate
function CellPhone() {
    this.cost = function () { return 397; };
    this.screenSize = function () { return 5; };
}
/*Decorator 1*/
function Camera(cellPhone) {
    var price = cellPhone.cost();
    cellPhone.cost = function() {
        return price + 45;
    }
}
 /*Decorator 2*/
function Wifi(cellPhone){
   //get cell phone current price
   var price = cellPhone.cost();
    
   //update cell phone cost() function
   //and add feature price to current price
   cellPhone.cost = function(){
     return  price + 90;
  };
}

 /*Decorator 3*/
function threeG(cellPhone){
   var price = cellPhone.cost();
   cellPhone.cost = function(){
     return  price + 90;
  };
}

/*Decorator 4*/
function Bluetooth(cellPhone){
   var price = cellPhone.cost();
   cellPhone.cost = function(){
     return  price + 50;
  };
}

Company introduced a new model with Camera, Wifi and bluetooth. Lets see how to decorate the object:

var newModelCellPhone = new CellPhone();
Camera(newModelCellPhone);
Wifi(newModelCellPhone);
Bluetooth(newModelCellPhone);
console.log(newModelCellPhone.cost());
console.log(newModelCellPhone.screenSize());

Conclusion

We have implemented Decorator Design Pattern which add behavior to an existing object without making any code changes to the underlying classes as you notice its follow the design principle of "Open for an extension, closed for the modification" Now if Pizza Corner add any new Topping serving the need to extend the system by implementing new decorator class and no need to existing system. If you have any question or feedback please post in comments.

You may also like to see:

Saturday, April 4, 2015

Design Patterns : Singleton - One & only ONE Object

You may also like to see:

What is Design Pattern?


In programming, a design pattern is a general solution to a commonly occurring problem you find again and again in software design. A design pattern is a template for solving a problem and it can be use in different situations.

Singleton Pattern


Singleton Pattern is the most known design pattern and it is the simplest in terms of class diagram. It contains only one class. Singleton is a class which can be instantiate only one time and same instance get utilize in complete application. Singleton class don't take any parameters while creating an instance then same object might not be usable if different parameters are passed to initialized the class. The singleton pattern gives global point of access to instance like global variable but we can create our object only when its needed.


When to use Singleton?


There are many objects in an application for which we need a same instance always for example: logging objects, caches, dialog boxes, thread pools, app-settings or registry settings objects and object handle devices like printer etc. In fact many of these objects may cause unexpected application behavior or cause overuse of resources if more than one instance get instantiate.

Is Singleton really an anti pattern?


Before going to actual implementation of Singleton pattern, there are some pitfalls with singleton pattern. It is really complex and difficult to write unit test for a singleton class. Because singleton object maintain the state so your multiple test cases can behave weird if you did not reset the global state of singleton class between two isolated test cases. The ideal way is to use IoC/DI container (i.e, spring etc). These containers allow you to create singleton instance but also give you the ways to modify this behavior according to situation like for unit tests.

Implementation of Singleton Pattern


Any public class can be instantiate as new Object() but if class is public then at any point new Object() will instantiate a new object of the class.

So that means if class is public we cannot stop the multiple instances of the class. What if we make the class private? Will this stop the multiple instances of class? NO, as private class often declared as nested class and can be accessible within parent class but there can be multiple instance of private class within parent public class. So making class private will not make it singleton.

What if we make the constructor of class private?

public Singleton
{
  private Singleton()
  {
  }
}

What does this code means? It cannot be instantiate as its constructor is private and can only be called within the class. So now we have a class which cannot be instantiate but for Singleton we need ONE OBJECT which is not possible in our code.

As we know private constructor can only be invoke within the class that means we actually can instantiate within the class. so what if we create a static method which returns us an object.

public Singleton
{
  private Singleton()
  {
  }

  public static Singleton GetSingletonInstance()
  {
     return new Singleton();
  }
}

Now we can get class instance using static function Singleton.GetSingletonInstance(); It is still returning new instance each time but now we can easily change the code to return the same instance:

public Singleton
{
  //private static variable to hold the instance
  private static Singleton _uniqueInstance = null;

  //private constructor can only be call within class
  private Singleton(){}

  //static function to get same instance always
  public static Singleton GetSingletonInstance()
  {
    if(_uniqueInstance == null)
    {
      _uniqueInstance = new Singleton();
    }
    return _uniqueInstance ;
  }

  //other required class methods
}

So now our code will check the static instance holder variable and if it is null which means it is not loaded before it will get initialize and will be return and for each next call same instance will be return.

So are we done with singleton? What if application has multiple threads? and two of threads at the same time called the Singleton.GetSingletonInstance();

Thread 1 will check if(_uniqueInstance == null) which will be true
Thread 2 will check if(_uniqueInstance == null) which will be true

So now we have two different instance of our Singleton object within two threads. So it is still not singleton object. Our above implementation is not thread safe.

In c# we can use lock to make it thread safe. Lock will make sure only one thread at a time can have access to instance initiator code.

public Singleton
{
  //private static variable to hold the instance
  private static Singleton _uniqueInstance = null;
  
  private static readonly object lockObject = new object();

  //private constructor can only be call within class
  private Singleton(){}

  //static function to get same instance always
  public static Singleton GetSingletonInstance()
  {
     lock(lockObject)
     {
       if(_uniqueInstance == null)
       {
         _uniqueInstance = new Singleton();
       }
       return _uniqueInstance ;
     }
  }

  //other required class methods
}

This implementation is thread safe as lock statement will make sure only one thread can use the code after locking it. Which means when thread 1 will invoke the lock() the second thread will be hang to use the code until thread 1 is completed with its executions.

As we can see it is thread safe but it will effect on performance as each time instance get requested lock will be created. But we actually need the lock for only first time when instance get initialized after that if multiple thread go for getting the instance at the same time will get the same instance as if(_uniqueInstance == null) will be false always.

How to optimize the performance?


If you think lock within GetSingletonInstance() will not cost you much, so there is no need to change in implementation. You are good with above code implementations. Otherwise you can do one of following options.

Without lock - Removing lazy instance creation


One option is to remove the lazy instance creation, instead we go with eager created instance.

public Singleton
{
  //private static variable with initialize instance
  private static Singleton _uniqueInstance = new Singleton();

  //private constructor can only be call within class
  private Singleton(){}

  //static function to get same instance always
  public static Singleton GetSingletonInstance()
  {
    //as we already initialize the static instance so just return it
     return _uniqueInstance;
  }

  //other required class methods
}

So now our static variable has the instance and it will be return for each thread. It is thread safe but it has removed the concept of on demand object creations which means your instance will be created whether your application need it or not.

Double checked locking


With double checked locking we firstly check whether instance is null or not.If it is null then we lock the inner-code. It means only first instance creation will require the lock after that all thread will get the same instance without lock.


public Singleton
{
  //private static variable to hold the instance
  private static Singleton _uniqueInstance = null;
  
  private static readonly object lockObject = new object();

  //private constructor can only be call within class
  private Singleton(){}

  //static function to get same instance always
  public static Singleton GetSingletonInstance()
  {
     if(_uniqueInstance == null)
     {
       //if _uniqueInstance is null then lock
       lock(lockObject)
       {
          //recheck here bcos if second thread is in queue it will get it false
          if(_uniqueInstance == null)
          {
             _uniqueInstance = new Singleton();
          }
       }
     }
     return _uniqueInstance ;
  }

  //other required class methods
}

So now if two thread gets if(_uniqueInstance == null) true only one thread will go forward to create the instance, second will wait for first thread to complete the execution.

Conclusion


As we noticed there are multiple ways to implement the singleton pattern and it is completely on the situation to opt the most suited option for the scenario. Each implementation has its pros and cons, so always go according to application situation.

You may also like to see:

Monday, February 24, 2014

JavaScript Best Practices: Why to avoid global variables and objects in JavaScript?

Learning AngularJS; Guide for beginners:

In this article I would try to explain the issue can be occurred due to global variable declaration if it is not declared global intentionally.

As we discussed in previous article JavaScript Best Practices : Strict mode In JavaScript if you are not using strict mode of ECMAScript 5 then assigning value to a variable which is not declared yet, then a global variable of that name will automatically be created.



See demo here.



(function() {
  myVar = 'Hello, Undeclared Variable!';
  alert(foo)  //=>; Hello, Undeclared Variable
})();

alert(myVar)  //=>; Hello, Undeclared Variable

So it is important to always declare your variables before initialization.

See demo here.

(function() {
  var myVar = 'Hello, Undeclared Variable!';
  alert(foo)  //=> Hello, Undeclared Variable
})();

//on accessing out side of scope ReferenceError: myVar is not defined
try {
  alert(myVar)
} 
catch (e) {
  alert("Error :" + e);
}

How it can cause error?


When global variables sneak into your code they can induce troubles. Particularly in applications with concurrency.

In the following example two different function using counter in loop without declaration which causes both to point same global variable.

see here without concurrency

var countOnetoTen = function() {
console.log("countOnetoTen started");
for (counter = 1; counter <= 10; counter += 1) {
         console.log(counter);
     }
 };
  countOnetoTen();  //=> 1 2 3 4 5 6 7 8 9 10

var countEleventtoTwenty = function() {
console.log("countEleventtoTwenty started");
for (counter = 1; counter <= 10; counter += 1) {
         console.log(counter+10);
     }
 };
  countEleventtoTwenty(); //=> 11 12 13 14 15 16 17 18 19 20// 
Both loops increment counter at the same time, which causes strange behavior in concurrency. With small amount of loops counter it is not observable, but it can be problematic in any case. As if two function working concurrently and accessing the same global variable. There can be a situation
  1. countOnetoTen() started set counter = 1
  2. countOnetoTen() : printed counter and increment counter++ //counter = 2
  3. countOnetoTen() : printed counter and increment counter++ //counter = 3
  4.  countEleventtoTwenty() started and set counter = 1
At this point counter is set to 1 while countOnetoTen() already have printed 1 2 and in next iteration it will find counter set to 1 and will print 1 again.
window.setTimeout(countEleventtoTwenty , 10);
window.setTimeout(countOnetoTen, 10);  //=> 2 3 7 8 9
  
this Keyword as global object

Sometime you can use 'this' in method definitions to refer to properties of the method's object.
var obj = {
prop: 'foo',
myFun: function() {
alert(this.prop);
}
};

obj.myFun();  //=> print foo
But 'this' does not conform the normal rules of scope in JavaScript. One might expect 'this' to be available with the same value via closure in the callback specified inside the method here. see here demo
var obj = {
  prop: 'foo',
  myFun: function() {
    window.setTimeout(function() {
      alert(this.prop);
    }, 3000);
  }
};

obj.myFun(); //=> alert undefined
Here in callback 'this' got bound to the global object which do not contains the definition of prop. To get around this, assign the object reference to a regular variable that will have the same value inside the callback definition. see here demo
var obj = {
prop: 'foo',
myFun: function() {
  var that = this;
  window.setTimeout(function() {
    alert(that.prop);
  }, 3000);
 }
};

obj.myFun();  //=> alert foo
The keyword 'this' is actually dynamically assigned whenever a function is invoked. When a function is invoked as a method, i.e. obj.method(), 'this' is bound to 'obj'. But when a function is invoked by itself 'this' is bound to the global object.
var text = 'Hello, world!';
var printText() {
alert(this.text);
}

printText();  //=> Hello, world!
This is true even of functions that were defined as a method.
var obj = {
  prop: 'foo',
  myFun: function() {
   alert(this.prop);
  }
};
When the subroutine is invoked without reference of object ie obj with it, 'this' becomes the global namespace.
var myFun = obj.myFun;
myFun();  //=> undefined
Method invocation and function invocation are two of the invocation patterns in JavaScript. A third is apply invocation, which gives us control over what 'this' will be assigned to during function execution.
myFun.apply(obj, null);  //=> foo
'apply' is a method on Function. The first argument is the value that 'this' will be bound to. Successive arguments to apply are passed as arguments to the function that is being invoked. The last invocation pattern in JavaScript is a constructor invocation. This Pattern was projected to offer a means to make new objects that would seem familiar to programmers who are used to programming with classes.
var Duck = function(name) {
this.name = name;
};
Duck.prototype = {
query: function() {
  alert(this.name + ' says, "quack"');
}
};
When a instance is created with new keyword in front of it, a new object is initiated and is linked to 'this' keyword when function executed.
var donald= new Duck('Donald');
  donald.query();  //=> donald says "quack"
When a new object is created with 'new', the prototype of the new object is set to the prototype of the constructor function. So the new object inherits all of the attributes of the constructor's prototype value. In this case, new duck objects inherit the 'query' method from Duck.prototype.
var daffy = new Duck('Daffy');
daffy.query();  //=> Daffy says "quack"
If a constructor function is called without the 'new' keyword, it is invoked with the ordinary function invocation pattern. So 'this' is assigned to the global object instead of to a newly created object. That means that any attributes assigned to the new object by the constructor function become global variables!
var gotcha = Duck('gotcha!');
gotcha.query();  //=> TypeError: gotcha has no properties
Constructor invocation is pretty complicated and prone to disastrous global variable creation. Here is a neater path to produce new objects that inherit from other targets This defines Object.create, a method that simplifies the behavior of the 'new' keyword. This method was invented by Douglas Crockford.
if (typeof Object.create !== 'function') {
Object.create = function(o) {
var F = function() {};
F.prototype = o;
return new F();
};
}
Object.create(obj) returns a new object that inherits all of the attributes of obj. The 'duck' prototype object here defines a 'clone' method that wraps around Object.create to customize new 'duck' objects as they are created.
var duck = {
query: function() {
print(this.name + ' says "quack"');
},
clone: function(name) {
var newDuck = Object.create(this);
newDuck.name = name;
return newDuck;
}
};

var buffy = duck.clone('buffy');
buffy.query();  //=> buffy says "quack"
In addition to inheriting 'query', new ducks also inherit 'clone'.
var buffy2 = buffy.clone('buffy2');
buffy2.query();  //=> buffy2 says "quack"
Methods and attributes are inherited, not copied. If you change the definition of 'clone' on 'duck' at this point, the change will be reflected in duck objects that have already been created.
buffy2.hasOwnProperty('clone')  //=> false
buffy.hasOwnProperty('clone')  //=> false
duck.hasOwnProperty('clone')  //=> true

Saturday, February 15, 2014

JavaScript Best Practices : ECMAScript 5 Strict Mode

JavaScript allows developer to do tricks which many other languages do not allow to code. This behavior of JavaScript sometime causes some confusion in JavaScript code and unexpected behaviors. To overcome this in ECMAScript 5 has introduced Strict mode which is supported with all latest browsers and also do not conflict with old browsers.

What Strict Mode is?

Strict Mode is a new feature that allows developer to place code in a strict operating context which prevents certain ambiguous and confusing action from being taken and prompt with more information by throwing exception.

Strict mode gives advantage to developer in following ways:
  • Strict mode disabled the feature which are confusing.
  • Strict mode throws exception on coding mistakes.
  • Strict mode prevent developers by throwing exception if unsafe actions like accessing global object are being made
ES5 specification has detailed information about change in [PDF] or you can see here.


How strict mode works?

Simple. Toss this at the top of a program to enable it for the whole script:
Using strict mode is simple, to make complete script file in strict mode put at the top of script:
"use strict";

Or to make certain functions or context to be strict put the string in that context.
function myFunctionToBeStrict(){
"use strict";
// ... your code ...
}
Enabling strict mode is really a simple just put the string at the top of your any script and that is it. If browser support the strict mode it will start working, and old browsers working with ECMAScript 4 or previous will ignore it as string and keep working as they were.

You can work in dual mode by placing all of your code to execute in strict mode in a context and made that context strict. All the code outside of that context will works in non-strict mode.
// Non-strict context...

(function(){
"use strict";

// strict code context...
})();

// Non-strict context...

What Strict Mode prevents you to code?

Variables

If you try assignment to variable (e.g, myVar = "hello undeclared function";) which is not declared will throw exception. Previously it allows to assign and create a property to global object (e.g, window.myVar). This really prevents some unexpected situation to occur.

see demo here

myVar = "hello undeclared function";
alert("Without strict mode ::: " + myVar);

(function () {
 "use strict";

 try {
 testVar = "hello undeclared function";
 alert("With strict mode ::: " + testVar);
 } catch (ex) {
 alert("Strict mode Exception ::: " + ex);
 } 
})();

Properties

ECMAScript made properties more easily manageable and prevent some coding bloop causing unexpected behavior.

1- adding a property to an object whose extensible attribute is set to false.

see demo here

var myObj = new Object();
Object.preventExtensions(myObj);
myObj.name = "Smith";

console.log("without strict mode ::: "+ myObj.name);

(function () {
 "use strict";

 try {
 var strictObj = new Object();
 Object.preventExtensions(strictObj);
 strictObj.name = "Smith";
 console.log(strictObj.name);

 } catch (ex) {
 console.log("Strict mode Exception ::: " + ex);
 }
})();

2- Attempt to change a property value whose writable attribute is set to false.

see demo here

var myObj = new Object();

Object.defineProperty(myObj, "myVar", {
 value: 10,
 configurable: false
});

delete myObj.myVar;
console.log("Without Strict mode ::: " + myObj.myVar);

(function () {
 "use strict";

 try {
 var myStrictObj = new Object();

 Object.defineProperty(myStrictObj, "myVar", {
 value: 10,
 configurable: false
 });

 delete myObj.myVar;
 } catch (ex) {
 console.log("Strict mode Exception ::: " + ex);
}
})();
3- Try delete a property whose configurable attribute is set to false.

see demo here

var myObj = new Object();

Object.defineProperty(myObj, "myVar", {
 value: 10,
 configurable: false
});

delete myObj.myVar;
console.log("Without Strict mode ::: " + myObj.myVar);

(function () {
 "use strict";

 try {
 var myStrictObj = new Object();

 Object.defineProperty(myStrictObj, "myVar", {
 value: 10,
 configurable: false
 });

 delete myObj.myVar;
 } catch (ex) {
   console.log("Strict mode Exception ::: " + ex);
 }
})();
will result in an error . Previously there was no error when any of these actions are attempted, it will just fail silently.

Deleting variable, function, or argument

Deleting a variable, a function, or an argument will result in an error.
var myVar = "test";
function myFunc(){}

delete myVar; // Error
delete myFunct; // Error

function myFunc2(myArg) {
  delete myArg; // Error
}
In large objects where you defined multiple properties there is possibility of coding duplicate property. With ECMAScript 5 strict mode defining a property more than once in an object literal will cause an exception to be thrown.
// Error because prop1 is twice
var testObj = {
    prop1: 10,
    prop2: 15,
    prop1: 20
};

eval in Strict Mode

The string "eval" cannot be used as an identifier (variable or function name, parameter name, and so on).
// All generate errors...
obj.eval = ...
obj.foo = eval;
var eval = ...;
for ( var eval in ... ) {}
function eval(){}
function test(eval){}
function(eval){}
new Function("eval")
Adding new variable using eval is not allowed in strict mode.
eval("var addVar = false;");
console.log( typeof addVar ); // undefined

Functions in Strict Mode


Attempting to overwrite the arguments object within a function will result in an error(also Arguments as an identifier is not allowed):
function myArgs(myArg) {
    arguments[0] = 20; //not allowed
}
Defining two arguments of identical name is not allowed.
function myArgs(myArg,myArg) {
   //code
}
Access to arguments.caller and arguments.callee now throw an exception. Thus any anonymous functions that you want to reference will need to be named, like so:
function (testInt) {
    if (testInt-- == 0)
        return;
    arguments.callee(testInt--);
}
Defining and calling arguments and caller properties of function is not longer exist.
function myFunc(){
function myInnerFunc(){
// Don't exist, either
myFunc.arguments = ...; // Error
myInnerFunc.caller = ...; // Error
}
}


Eliminates this Coercion


Another important change is a this-value of null or undefined is no longer coerced to the global. Instead, this remains its original value, and so may cause some code depending on the coercion to break.


For example:


window.prop = "foo";
function sayProp() {
    alert(this.prop);
}

// Throws an error in strict mode, "foo" otherwise
sayProp();

// Throws an error in strict mode, "foo" otherwise
sayProp.call(null);
this value of any context must be assigned a value or else it remains undefined, so calling object without new keyword also throw error:
function Person(name) {
    this.name = name;
}

// Error in strict mode
var me = Person("Smith");
Since this is undefined causing error.

with(){}

with(){} statements are not usable when strict mode is enabled. It cause syntax errors.
with (location){
  alert(href);
}

Saturday, January 11, 2014

JavaScript Best Practices : loop optimization

You may also like to see:

As JavaScript is a client sided programming language, JavaScript should not do any complex or really difficult algorithms which take a lot of time computation.As it may cause to hang the browser or affect your site performance.


There are many things to optimize in a code, In this article I will try to discuss some techniques using we can optimize loops in JavaScript.



A simple loop in JavaScript is:



var fruits = ["apple","banana","orange","mango"];
for(var i = 0; i < fruits.length; i++) {
  // do something with fruits[i]
}

See Performance Demo here

This is simplest loop, we don't need to optimize it but if there are a huge number of items in the array to iterate on or there is complex logic in loop to implement, then we might need to make it faster. Following are some optimizations we can implement on this loop.  

Cache the condition to break

This loop will break when variable i is equals to length of the array, each time array checks this condition it will get the length from object, which is just a overhead. We can get the length of the array and assign it variable and use that variable so we don't need to calculate the length each time. This small trick is really beneficial when iterating over huge items.

var fruits = ["apple","banana","orange","mango"];  
for (var i = 0, max = fruits.length;i < max; i++) {    
   // do something with fruits[i] 
} 

See Performance Demo here

Now this will initialize once then it will use the max variable in each iteration.

(Note: Here initialization of i and max is separated with comma not semi-colan var i = 0, max = fruits.length;  

Single var Pattern

According to single var pattern:
Initializing all variable with single var at common place helps to control the scope of variables and avoiding collisions of variable names, unused variables or preventing logical issues due to uninitialized items. If there are 1000 variables and you initialized it with single var keyword, will save your more than 3000 characters which make your code lesser in size and make it even readable after minifying with some tool.

Using a single var for initialization of all the variable include in iteration can further optimize the performance, with a minor drawback of making copy-paste harder for a loop when refactoring a code.

var i, max, fruits = ["apple","banana","orange","mango"]; 
for (i = 0, max = fruits.length;i < max; i++) {
   // do something with fruits[i]
}

Making simplest increment  

i++ is a bit tricky operator what it actually do:
  • make a temporary copy of variable i
  • increment variable i
  • return the temporary copy for current use
so replacing this with i += 1 or i=i+1 will effect the loop positively.

var i, max, fruits = ["apple","banana","orange","mango"]; 
for (i = 0, max = fruits.length;i < max; i+=1) {
   // do something with fruits[i]
}

See Performance Demo here

Reverse loop

If we iterating over a loop for all the elements in a collection reverse loop starting from a length of collection to zero is faster than above given techniques, it completely depends on the situation whether to use this technique or not. As zero in JavaScript is equal to false so it will automatically break the loop on zero. In this technique condition testing and decrement is occurring in one step which making performance faster.

var i, fruits = ["apple","banana","orange","mango"]; 
for (i = fruits.length; i-=1;) {
   // do something with fruits[i]
}

See Performance Demo here

Making cleaner while-loop

If reverse loop iteration is possible then making it as while loop is more cleaner, it would not make code faster but will surely make it cleaner, readable, easy to understand.

var fruits = ["apple","banana","orange","mango"],i = fruits.length;
while(i-=1) {  //for readability use i--
   // do something with fruits[i]
}


See decrement operator performance difference here.

Summary

It is not necessary that you always get benefits from using these best practices as in small collection all above techniques might produce performance but when you are implementing complex algorithms with a number of collections then you will get the benefits of good code. So making it practice to use best practices always, will make your code and performance better even when you not realize it.


You may also like to see:

Sunday, November 24, 2013

Best Resources to Learn JavaScript

You may also like to see:

If you want to learn JavaScript and need some good tutorial, Here I listed some nice resources to be refer.

Videos

The best resources are the videos from Douglas Crockford:

Crockford on JavaScript
  1. Volume One: The Early Years
  2. Chapter 2: And Then There Was JavaScript
  3. Act III: Function the Ultimate
  4. Episode IV: The Metamorphosis of Ajax
  5. Part V: The End of All Things
  6. Scene 6: Loopage
The JavaScript Programming Language
  1. The JavaScript Programming Language Part 1
  2. The JavaScript Programming Language Part 2
  3. The JavaScript Programming Language Part3
  4. The JavaScript Programming Language Part4

An Inconvenient API: The Theory of the DOM
  1. Theory of the DOM Part 1
  2. Theory of the DOM Part 2
  3. Theory of the DOM Part 3

Advanced JavaScript
  1. Advanced JavaScript" (1 of 3)
  2. Advanced JavaScript" (2 of 3)
  3. Advanced JavaScript" (3 of 3)

Object Oriented Programming in JavaScript

  1. Part 1 : Object Oriented Programming & JavaScript
  2. Part 2: Object Oriented JavaScript : Classes, Methods and Properties
  3. Part 3: Object Oriented JavaScript : Inheritance, Polymorphism and Encapsulation

Books

  1. JavaScript: The Good Parts by Douglas Crockford
  2. John Resig's book Pro JavaScript Techniques for the more advanced stuff.
  3. Javascript: The Definitive Guide to be of great help
  4. Online book Eloquent JavaScript by Marijn Haverbeke
  5. Essential JavaScript Design Patterns For Beginners by Addy Osmani
  6. Head First HTML5 Programming:Building Web Apps with JavaScript

Learning Sites

  1. Douglas Crockfords writings on JavaScript.
  2. comp.lang.javascript FAQ is quite a nice resource.
  3. Learn appendTo created for learning JavaScript. 
  4. J Resig, Secrets of the javascript ninja
  5. bonsaiden's Javascript Garden quick walk through
  6. Codecademy is interactive - it's pretty sweet

Articles

  1. A re-introduction to JavaScript
  2. Mozilla Developer Center.
  3. Data Types in JavaScript 
  4. JavaScript Best Practices : === vs == 
  5. JavaScript Prototype and Inheritance 
  6. Currying in JavaScript 
  7. How Prototype works?
  8. Is JavaScript's "new" Keyword Considered Harmful?
  9. Pass by reference / value 
  10. This keyword
  11. Teaching JavaScript
  12. "Let's Make a Framework" series on DailyJS.
  13.  Module pattern
  14. Closures

You may also like to see:
Life insurance policy, bank loans, software, microsoft, facebook,mortgage,policy,