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:

Monday, January 19, 2015

AngularJS : On click redirect to another page

You may also like to see:

Besides the fact, AngularJs is Single Page Application, but we use URL routes for bookmarks and for better user experience. An application navigates around the different UI views for different features and actions. Since AngularJs is doesA it do not reload the complete page on each route change but it loads only the HTML for the current page and inject into our current page.

In AngularJs application if you want to redirect the application to another page of the application, and if your navigation element is an anchor tag then you can simply assign new route's URL to href attribute of the tag.

Dashboard

But if your element to navigate is not anchor tag then you need to write a scope function which redirects to your required page and you invoke this function on your element click.

  • Drafts

  • and define that function in controller as:

    $scope.redirectToDraftPage= function () {
       $location.path('/draft');
    };
    

    As you can see it is really annoying to write a scope function for each navigator items. So best way to achieve redirection in AngularJs on element click is to write a directive for this.

    Directives


    Directives are the custom tags and attributes, it is a way to extend HTML functionality. You can teach HTML new features using directive tags. AngularJs have many directives like ng-show, ng-app, ng-repeat, ng-class, ng-hide and many more.

    For more details on directive see this article.

    Directives are HTML tags and attributes. These are the way to use AngularJS extended HTML functionality. Using directives you can teach HTML new features by writing your own custom directives. AngularJS comes with a bunch of built-in directives like ng-app, ng-hide,ng-show, ng-repeat, ng-class and many others.

    Include a directive to your application, with restrict: 'A' defining that this directive is actually an extending Attribute, so whenever an element has this custom directive as attribute my defined functionality will be executed accordingly.

    So what this directive will do? It will assign a click event to that particular element which has this attribute. And it will redirect to the provided route onclick of the element.

    (function(){
    
        'use strict';
    
        function ngRedirectTo($window) {
            return {
                restrict: 'A',
                link: function(scope, element, attributes) {
                    element.bind('click', function (event) {
                        //assign ng-Redirect-To attribute value to location
                        $window.location.href = attributes.ngRedirectTo;
                    });
                }
            };
        }
        angular.module('app').directive('ngRedirectTo', ngRedirectTo);
        //inject $window service for redirection
        redirectTo.$inject = ['$window'];
    }());
    
    

    As naming convention for directive work as each camel-case word separated by hyphen( ie, - ). so our directive ngRedirectTo will be use in html as ng-Redirect-To. Here is the html:

     Dashboard 
    

    So now you include this directive to your index page and you can reuse this in your whole application wherever you want to navigate. Just add this attribute to the element and assign the route to it.

    If you have any feedback or suggestions or you want to add something to this article please post in comments.

    You may also like to see:

    Saturday, January 3, 2015

    Interceptor in AngularJs : Global Session & Overlay (Preloader) handling

    You may also like to see:

    Every AngularJs application communicates with remote server by making http calls and get the data in form of JSON or XML from remote server and than this data will be show to users with html.

    If your application need to interact with the remote HTTP server then AngularJs has $http service for you. It allows to communicate with backend remote web APIs using JSON or XMLHttpRequest.


    Here is the general get call using $http service:

    // Simple GET request example
    $http.get('/api/url').
    success(function(data, status, headers, config) {
    // asynchronous callback event will be trigger
    // when the call to URL is successful.
    }).
    error(function(data, status, headers, config) {
    // asynchronous callback event will be trigger
    // when en error occurred calling URL or server returns
    // response with error status.
    });
    
    post call using $http service:
    // Simple POST request example
    $http.post('/api/url', {data:'hello! Its post call data!'}).
    success(function(data, status, headers, config) {
    // asynchronous callback event will be trigger
    // when the call to URL is successful.
    }).
    error(function(data, status, headers, config) {
    // asynchronous callback event will be trigger
    // when en error occurred calling URL or server returns
    // response with error status.
    });
    

    There are many scenarios when you need to capture and make some changes to each request for example you want to insert session token to each web request for the authorization similarly you may need to capture each response to perform some actions on data like global error handling for API calls Interceptors are created for these scenarios.

    Interceptors


    $httpProvider contains an array of registered interceptors. Interceptor is an AngularJs factory, you can register it by pushing to httpProvider interceptor array in your application configurations.

    There are four different interceptors you can handle, and these four functions should be in your interceptor factory if you need to perform custom operations in it:
    1. Request Interceptor:

      A request interceptor will be invoke on each request initialization, you can change request data here like adding authorization token.
    2. Response Interceptor:

      A response interceptor will be invoke on each response from remote server, you can manipulate response here like checking pushing some data to response perform some operations on response values.
    3. Request Error Interceptor:

      A request error interceptor will be invoke if there is some error while requesting remote server, like missing header or internet disconnection. Here you can validate request and resend the request to remote server.
    4. Response Error Interceptor:

      A response error interceptor will be invoke if there is error on backend remote calls like some unhandled exception on server. Here you can handle the request by showing proper message to user or resend the request to same url or alternate if available.

    Here is the example of Interceptor factory with all above interceptor functions:

    // Interceptor example for angularJs.
    angular.module('app').factory('customInterceptor', ['$q', function($q) {  
    
    var myInterceptor = {
    request : request,
    requestError : requestError,
    response : response,
    responseError : responseError
    };
    
    // On request success
    request: function (config) {
       // Contains the data about the request before it is sent.
       console.log(config);
    
      // Return the config or wrap it in a promise if blank.
      return config || $q.when(config);
    };
    
    // On request failure
    requestError: function (rejection) {
      // Contains the data about the error on the request.
      console.log(rejection);
    
    // Return the promise rejection.
    return $q.reject(rejection);
    };
    
    // On response success
    response: function (response) {
      // Contains the data from the response.
      console.log(response); 
    
    // Return the response or promise.
    return response || $q.when(response);
    };
    
    // On response failture
    responseError: function (rejection) {
      // Contains the data about the error.
      console.log(rejection);
    
    // Return the promise rejection.
    return $q.reject(rejection);
    };
    
    return myInterceptor;
    }]);
    
    and then register it to $httpProvider interceptor array.
    angular.module('app').config(['$httpProvider', function($httpProvider) {  
       $httpProvider.interceptors.push('customInterceptor');
    }]);
    

    Examples


    Authentication Token Injector


    If you are using token based authentication for web APIs in which on authentication call server return you a token & this token is required for all the further calls so server. So now you need to provide this authentication token to all the request so here we can use the interceptor. For this we need request interceptor and need to insert token to request.

    angular.module('app').factory('authTokenInjector', ['authenticationService', function(AuthenticationService) {  
        var authTokenInjector = {
            request: function(config) {
                if (!AuthenticationService.isAnonymus) {
                    config.headers['x-session-token'] = AuthenticationService.securityToken;
                }
                return config;
            }
        };
        return authTokenInjector;
    }]);
    


    Now register it to interceptors by pushing it to $httpProvider interceptor array. After this each call will be intercepted and authToken get injected to header. It is global handling for authentication now no need to handle it for individual call.

    Overlay/Pre-loader to show


    You want to show overlay on your page unless all the calls gets completed. For this instead of handling it manually you can write it in interceptors and let this work for your complete application.

    To achieve this you can write html on your main index page for loader:

    
    
    and html:


    Now write the interceptor factory, which will show the loader when call get started and hide when all the calls get executed.But As you know there are multiple calls on a page so we will use a counter which will be incremented on each request and loader will be hide when request counter is zero:
    // Interceptor example for angularJs.
    angular.module('app').factory('overlay', ['$q', function($q) {  
    
      //initialize counter
      var requestCounter=0;
    
      var myInterceptor = {  
         request : request,
         requestError : requestError,
         response : response,
         responseError : responseError
      };
    
       // On request success
       request: function (config) {
    
        //will be incremented on each request
        requestCounter++;
    
        //show loader if not visible already
        if(!$('#preloader').is(':visible')){
            $('#preloader').show();
        }
    
        // Return the config or wrap it in a promise if blank.
        //it is required to return else call will not work
        return config || $q.when(config);
      };
    
      // On request failure
      requestError: function (rejection) {
    
         //decrement counter as request is failed
         requestCounter--;
         hideLoaderIfNoCall();   
    
         // Return the promise rejection.
         return $q.reject(rejection);
      };
    
      // On response success
      response: function (response) {
          
         //decrement counter as request is failed
         requestCounter--;
         hideLoaderIfNoCall();
    
         // Return the response or promise.
         return response || $q.when(response);
      };
    
      // On response failture
      responseError: function (rejection) {
      
    
         //decrement counter as request is failed
         requestCounter--;
         hideLoaderIfNoCall();
    
         // Return the promise rejection.
         return $q.reject(rejection);
      };
       
      function hideLoaderIfNoCall(){
         // check if counter is zero means 
         // no request is in process
     
         // use triple equals see why http://goo.gl/2K4oTX
         if(requestCounter === 0)  
            $('#preloader').hide();        
         }
    
      return myInterceptor;
    }]);
    

    Summary


    In this article we have seen what interceptors are,  try to explain different kinds of interceptor functions and what their usages are. We also implemented session injector example in which we intercepted request and injected auth token to each request. We also implemented example to globally handling the overlay on page while requests are in process.

    Please write your feedback and suggestions in comments.

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