Friday 28 October 2011

KnockoutJs

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that update dynamically, KO can help you implement it more simply and maintainably.

Read here for more information on KnockoutJs.

Implementation:

Now in this post, assuming you have read about KO, I want to show you how you can populate a dropdown list from the server and change text when a value is selected.


Please take note, I did this using . Net MVC 3. Now, i have two ActionResult function that return a Json object. The "studentObj" is an anonymous object that has two properties, student and rankings. Student is the student object with a ranking of  "Average". The rankings, is a list of Ranking that can be awarded to a student.

This is how we are going to display the information on the client side:





These are the results, when page loads for the first time:

And when student is ranked:


I am sure you can agree that this is a cleaner way of changing text depending with the action or event. Try to do this the normal way you were used to doing it and compare, i am sure you will be amazed.

Friday 21 October 2011

Creational Design Pattern - The Singleton Pattern

A singleton is a class which only allows a single instance of itself to be created, and usually give simple access to that instance, hence the name single-ton. Singletons don’t allow any parameters to be specified when creating the instance because a second request for an instance but with a different parameter could cause problems. If the same instance should be accessed for all requests with the same parameter, the factory pattern is more appropriate.

There are different ways of implementing the singleton pattern in any language, however for this post; I am going to show you how to implement it in JavaScript. With JavaScript, singletons serve as a namespace provider, which isolate implementation code from the global namespace so as to provide single point of access for functions.
The singleton doesn’t provide a way for code that doesn’t know about a previous reference to the singleton to easily retrieve it – it is not the object or class that is returned by a singleton, it is a structure. For instance, closured variables are not actually closures but the function scope that provides the closure is the closure.
In its simplest form, a singleton in JS can be an object literal grouped together with its related methods and properties as follows:
var mySingleton  = {

Name:”Tendai”,
Surname:”Bepete”,
getFullname:function(){
      return this.Name + “ “ + this.Surname;
}

};

You can extend this further by adding private members and methods to the singleton by encapsulating variable and function declarations inside a closure:
var mySingleton = function(){
          var privateAge = 18; //something private like your age or salary
          function showPrivateAge(){
               console.log(privateAge);
          }     
return{
         showAge:function(){ // you can now make it public knowledge
             showPrivateAge();
         },
         Name:”Tendai”, //this the public can see
         Surname:”Bepete”,
         getFullname:function(){
            return this.Name + “ “ + this.Surname;
        }
} ;

};

var single = mySingleton();
single.showAge(); // logs something private - age;
console.log(single.Name); // logs Name;
Now let us consider a situation where the singleton is instantiated when it is needed.


























Calling public methods is easy as follows: mySingleton.getInstance().getFullname();

How can the singleton pattern be useful? It is useful when exactly one object is needed to coordinate patterns across the system. Here is an example:

























var singletonTest = SingletonTester.getInstance({pointX:20});
console.log(singletonTest.PointX); // outputs 20

Hope this has been helpful. Welcome to comments and suggestion.

Monday 17 October 2011

Creational Design Pattern - Factory Pattern

To understand further about design patterns, let us look at what design is and what pattern is. Design is a blue print or sketch of something so it can be referred to as a creation of something in mind. Pattern, on the other hand, is a guideline or something that repeats. Now combining this, design patterns becomes creating something in mind that repeats or in other words capturing design ideas as a "pattern" to the problems.  


Now in this post I will look at one of the categories of design patterns and an example. Creational patterns define the best possible way in which an object can be instantiated. This describes the best way to create object instances. There are different types of Creational patterns and in this post we are going to look at the Factory pattern.

Factory Pattern

Factory of what? Of classes. In simple words, if we have a base class and a  number of sub-classes, and based on the data provided, we have to return the object of one of the sub-classes, we use a factory pattern. Here is an example:

In  this example, we use an abstract class as the base. The Ford, Toyota and BMW classes derive from the abstract class Vehicle.

abstract class Vehicle
{   
   abstract string Make {get;}
}

public class Ford : Vehicle 
{
      public override string Make
     {
        get
        {
           return "Ford";
        }
     }
}

public class Toyota: Vehicle 
{
      public override string Make
     {
        get
        {
           return "Toyota";
        }
     }
}

public class BMW: Vehicle 
{
      public override string Make
     {
        get
        {
           return "BMW";
        }
     }
}

static class Factory
{
    public static Make Get(int id)
    {
        switch(id)
        {
           case 0:
              return new Ford();
           case 1:
           case 2:
             return new Toyota();
           case 3:
           default:
             return new BMW();
       }
 }

static void Main()
{
    for(int i = 0; i <=3; i++)
    {
       var vehicle= Factory.Get(i);
       Console.WriteLine("Where id  = {0}, position = {1} ", i , vehicle.Make);
     }
}

Here is the Output 

Where id = 0, position = Ford
Where id = 1, position = Toyota
Where id = 2, position = Toyota
Where id = 3, position = BMW

The factory design pattern is found in the Factory class. The point of the Get method is to take a value and instantiate a class based on that value. It translate integers to objects with a switch statement. Because Ford, Toyota and BMW all derive from the same abstract class, the return type Make can be used. An implicit cast automatically casts the Ford, Toyota and BMW to Make references.

The Main method serves to demonstrate the Factory class in action. We use as part of the demonstration the integers 0, 1, 2 and 3. We user Get method with each of these values. Then, we show that the appropriate type of class was instantiated for each integer.

In short, the Factory patterns can be used in the following cases:

a) When a class does not know which class of objects it must create.
b) A class specifies its sub-class to specify which objects to create.
c) In programmer's language, you can use factory pattern where you have to create an object of any one sub-classes depending on the data provided.





Saturday 15 October 2011

Design Patterns

In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations.

Design patterns are represented as relationships between classes and objects with defined responsibilities that act in concert to carry out the solution. To illustrate a design pattern, consider the Adapter pattern. Adapter provides a solution to the scenario in which a client and server need to interact with one another, but cannot because their interfaces are incompatible. To implement an Adapter, you create a custom class that honours the interface provided by the server and defines the server operations in terms the client expects. This is a much better solution than altering the client to match the interface of the server.

Why Design Patterns

Design patterns can speed up the development process by providing tested, proven development paradigms. Effective software design requires considering issues that may not become visible until later in the implementation. Reusing design patterns helps to prevent subtle issues that can cause major problems and improves code readability for coders and architects familiar with the patterns.

Often, people only understand how to apply certain software design techniques to certain problems. These techniques are difficult to apply to a broader range of problems. Design patterns provide general solutions, documented in a format that doesn’t require specifics tied to a particular problem.

In addition, patterns allow developers to communicate using well-known, well understood names for software interactions. Common design patterns can be improved over time, making them more robust than ad-hoc designs.

There are three basic classifications of patterns Creational, Structural and Behavioural patterns.

Creational Patterns
Creational design patterns are design patterns that deal with object creation mechanism, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation.

Some examples of creational design patterns include:

Abstract factory pattern: centralize decision of what factory to instantiate

Factory method pattern: centralize creation of an object of a specific type choosing one of several implementations

Builder pattern: separate the construction of a complex object from its representation so that the same construction process can create different representations

Lazy initialization pattern: tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it in needed

Object pool pattern: avoid expensive acquisition and release of resources by recycling objects that are no longer in use

Prototype pattern: used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects

Singleton pattern: restrict instantiation of a class to one object

Structural pattern
Structural design patterns are design patterns that ease the design by identifying a simple way to realize relationship between entities.
Examples of Structural Patterns include:
Adapter pattern: adapts one interface for a class into one that a client expects
Composite pattern: a tree structure of objects where every object has the same interface
Aggregate pattern: a version of the Composite pattern with the methods for aggregation of children
Decorator pattern: add additional functionality to a class at runtime where subclassing would result in an exponential rise of new classes
Façade pattern: create a simplified interface of an existing interface to ease usage for common tasks.

Behavioural pattern
Behavioural design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.
Examples of this type of design pattern include:
Command pattern: command objects encapsulate an action and its parameters
Interpreter pattern: implement a specialized computer language to rapidly solve a specific set of problems
Iterator pattern: iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation