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 have 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.

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 different interface of each class.

Understanding Adapter pattern is not difficult because it work same as we see adapter in real world. 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 converts the power to required range.

Adapter in Programming


Lets 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. Team has designed an interface which is implemented by Facebook, Twitter and Linkedin classes. System is using this interface to switch between these sites and share the content. Developers have 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 list and team know to implement the same interface you have to understand APIs and have to put huge effort in implementations. But you found that Google + has already developed a library so you downloaded that library and try to integrate in your system.


There is a little problem Google+ developers have implemented their own interface which is not compatible with information sharing system. Here is 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. Lets 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 adaptee 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 class diagram of Adapter Pattern


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

Special Scenario


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

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 flexible replacement to sub-classing for extending functionality to an object.

If you think inheritance is everything than decorator pattern help you to learn the power of extension at run-time instead of compile-time. Lets 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 many 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 than 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 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 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. Lets 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


Lets implement the decorator pattern in JavaScript. Lets 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 feature has some cost. They want to to implement their system in a way they don't need to change 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 extension, close for 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 25, 2015

What Google says about your favorite Programming Language / Framework

You may also like to see:


Google autocomplete suggestion give you popular searches for your typed word. Here I search about different programming languages and frameworks. See what Google suggested me.

Some suggestion are really nice but some are.... see.

Why your favorite Programming Language is so ...

Java is so:


C language is:



C++ is hard:


Objective C is not that ugly:


Here is C#:


My favorite JavaScript is so:


PHP is so:


Google suggest Python is :


Visual Basic is so:


AngularJs is so:


ActionScript is so:

ASP.NET is so:

Clojure is so:

Is coffeescript better than JavaScript?


Delphi is so:

Fortran is faster:

For Google F# is still relate music:

Haskell is so:


jQuery is so:

Matlab is expensive:


Perl is so:


Ruby is so bossy:


Scala is so:


YII is so:


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:
Life insurance policy, bank loans, software, microsoft, facebook,mortgage,policy,