Friday, 4 November 2011

Should We Support Old Browsers?

A lot has happened over the past 10 years. Browsers have evolved to adapt to new web technologies. From a user’s perspective, they are now faster, simple and easy to upgrade. On the other hand, from a developer’s view, it is now easy and faster to develop the look and feel of web applications.

For instance, let us look at one of CSS 3 new feature, box-shadow. The box-shadow, as the name implies, creates a shadow, for instance, on a rectangular div. Now in previous versions you would have to add an image to do that. This feature is supported in IE-9, Firefox 4+ and Chrome 3+ (and other browsers I did not mention).
Another example I can add is Html 5 which again has new elements and features that are supported in newer versions of browsers. Let us look at the input element as an example. You can now specify a text-input as an email. I am referring to it as a text-input because in older browser like IE-6, it will be rendered as a text-box. Now with this there is no need to add validation on the control to check if the value is a valid email. This is all taken care of for you.
These are just a few simple examples that I can point out, but there are a lot more benefits we can reap from using new browsers. Now as a developer you will be tempted to develop web applications or static sites that can only be rendered nicely in these new browsers. You would be impressed with what you would have accomplished in a short period of time and this will only last up to until you get a phone call from a client telling you that the design is not good or that validation is not working. Only to realise that you did not cater for old browsers.
Let us look at the box-shadow again as an example. Now as a fall-back plan you would put a background image that would show the shadow. With the email you would add a JavaScript validation to make sure that the value entered is a valid email. All this could be avoided. How? From the word go, develop bearing in mind there are people still using old browsers. Or simply ask your client to upgrade to new browsers which I would advocate for.
I think it is time we start to educate our clients the benefits of upgrading to new browsers. Not only does it cut development time, but it will also give them a good user experience. This is a win-win situation for all of us. I would also like to hear your thoughts on this.

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



Thursday, 29 September 2011

Extension methods

What are Extension Methods?

Extension methods allow you to extend an existing type with new functionality, without having to sub-class or recompile the old type. Extension Methods help blend the flexibility of "duck typing" support popular within dynamic languages today with the performace and compile-time validation of strongly-typed languages. This is a cool feature of C# 3.0

Extension Method Example:

Lets say you want to check if a variable string is a valid telephone number. In this example, our valid telephone number must start with a zero and followed by 9 more digits or start with a zero followed by two digits a space three digits a space and four digits (0787845122 or 078 784 5122). You would normally implement this by calling a separate class (most likely a static method) to check to see whether the string is valid, for instance:

string telephone = txtTelephone.Text;

if ( MyValidator.IsValidTelephone(telephone) ) {

}

Now using extension method, i can add a useful IsValidTelephone() method onto the string itself, which returns whether the string instance is a valid string or not. I can then re-write the above code to be cleaner and more informative like:






















Note that the static method above has a "this" keyword before the first parameter argument of type string. This tells the compiler that this particular Extension method should be added to objects of type "string". Within the IsValidTelephone() method implementation i can then access all of the public properties/methods/events of the actual string instance that the method is being called on, and return true/false depending on whether it is a valid telephone or not.
Hope you enjoyed this post, will add some example in the next post.

Thursday, 15 September 2011

Linq equivalent to SQL Select Count and Group by

In this post i want to show you how you can do a select count and group by using LINQ that is equivalent to SQL's.
















We have our object Student and we are going to create a list of Students. Now we want to return a list of Students who are in a certain Class and the number of Students in that Class. To do that we are going to use the GroupBy method and use a lambda expression to return the group of Students in a Class as a list. From the list we can then select the Class name and the Count. Take note that I used an anonymous type in the Select method.




Now if we want to group by more than one field, for instance, Subject in this case here is how we can do it:


Results:



Hope you found this post useful. Like to hear from you for suggestions or questions.