1/25/14

Adapter Design Pattern

The Adapter design pattern is one of the most basic structural design patterns and it's definition is as follows:

"Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces."

Last week I was working on a part of a web application that pulled a list of users from the Database. This application has a pretty good amount of traffic and as the traffic increased it started putting a lot of load on the DB and slowing down the application. In an attempt to find a viable solution, we decided to try out an in-memory cache to store the user data and speed up access. About 25% of the traffic would get the data from the Cache and the rest would continue to go to the Database.

The code changes for the cache repository had to fit seamlessly into the existing design and the changes had to be made without touching the existing implementation for DB calls. The Adapter pattern turned out to be a perfect choice for the requirement.

Following is the code with just the call to the Database:

public class DbRepository
{
  public IEnumerable<user> GetUsers(int userId)
  {
    //call DB and get data
  }
}

//code calling the repository
public class UserService
{
  public IEnumerable<user> GetAllFriendsFor(int loggedInUserId)
  {
    //call DB repository to get data
   DbRepository repository = new DbRepository();
   return repository.GetUsers(loggedInUserId);    
  }
}

Following is the code after implementing the Adapter design pattern:

public interface IRepository
{
  IEnumerable<user> GetUsers(int userId);
}

public class CacheRepository:IRepository
{
  public IEnumerable<user> GetUsers(int userId)
  {
    //call cache and get data
  }
}

//the adapter
public class DbRepositoryAdapter:DbRepository,IRepository
{
}

public class RepositoryFactory
{ 
  //a variable that determines if the user is in test
  bool UserInCacheTest {get;set;}
  
  //return the appropriate repository
  public IRepository GetRepository()
  {
    if(UserInCacheTest)
   return new CacheRepository();
 
 return new DbRepositoryAdapter();
}
}


//code calling the repository
public class UserService
{
  public IEnumerable<user> GetAllFriendsFor(int userId)
  {
    //call the factory to get the appropriate repository
   IRepository repository = new RepositoryFactory().GetRepository();
   return repository.GetUsers(userId);    
  }
}
Explanation:

  • We create a new interface called IRepository that has a single method. This method will have the same signature as the method in the exisiting DbRepository since we are going to be adapting that repository to fit into the new design. NOTE: Using the same signature as in the existing DbRepository is just a matter of convenience, it is not necessary to do so.
  • We then create a new repository called DbRepositoryAdapter that will inherit from the existing DbRepository and implements the IRepository interface.The DbRepository already has a method with the same signature as the method in IRepository, so it is safe to say that the DbRepositoryAdapter implements the IRepository interface. NOTE: If the signature of the interface method was different, we would need to implement that method and call the DbRepository's method from inside it.
  • We create a new class called CacheRepository that also implements IRepository. 
  • We create a factory class called RepositoryFactory that will return a repository of type IRepository depending on whether the user is in the cache test. 
  • The CacheRepository and the DbRepositoryAdapter both implement IRepository, so we can use interface polymorphism within the UserService to return the appropriate repository.
  • We have incorporated the existing DbRepository into our new design by creating an adapter class on top of it. This way the existing DbRepository class and the new CacheRepository class can work well together.(NOTE: we have not touched the existing DbRepository in any way.). This is the advantage of using the Adapter design pattern.

3/10/13

Generic Contravariance in C#

In my previous post .NET interfaces Part 3 I had written about the IEqualityComparer interface which has the following signature:

 public interface IEqualityComparer<in T>
 {
        bool Equals(T x, T y);        
        int GetHashCode(T obj);
 }
 
The keyword "in" before the type T indicates that this interface is contravariant.

In the same post we were calling the Contains method on a collection of type FootballStar as shown below:

FootballStars.Contains(Peyton2,new StarComparer())
We were passing in an instance of type IEqualityComparer<Star> to a method that was expecting an IEqualityComparer<FootballStar> i.e we were able to pass a less derived type than was specified by the type parameter.

This was possible because the interface IEqualityComparer<in T> is a contravariant interface that allows us to pass a less derived type than the specified type parameter.

Even though we are passing in a less derived type, everything works perfectly because the instances that ultimately get passed to the Equals method of the IEqualityComparer method are still of type FootballStar(since the collection is of type FootballStar), which derives from Star.

If the interface was not Contravariant, we would have to create a new IEqualityComparer of type FootballStar and pass that to the contains method. The compiler will not have it any other way. We would also have to repeat this for every type that derived from Star, assuming that all instances of type Star(e.g. FootballStar, BaseballStar) wish to use the same logic to determine the equality of their instances.

We would end up writing code like this:

//a comparer for FootballStar instances
public class FootballStarComparer:IEqualityComparer<FootballStar>
{
}
//that will be passed to contains FootballStars.Contains(Peyton2,new FootballStarComparer())

//a comparer for BaseballStar instances public class BaseballStarComparer:IEqualityComparer<BaseballStar> { }
//that will be passed to contains BaseballStars.Contains(bbStar1,new BaseballStarComparer())
So instead of using the type inheritance heirarchy and polymorphism we would be writing a lot of repititive code to perform similar tasks.

3/9/13

.NET interfaces Part 3

IEqualityComparer<T>

 public interface IEqualityComparer<in T>
 {
        bool Equals(T x, T y);        
        int GetHashCode(T obj);
 }
 
When to use it:
Let us say you have a custom Type and you plan to use instances of that type in a collection. If you want to use methods like List<T>.contains or Dictionary<T1,T2>.Add, you will need to way to check if an item in your collection equals the item we are trying to find.To facilitate this you can implement the IEqualityComparer<T>.

How is it different from IEquatable<T>?
For every custom type that you wish to check for Equality, you will need to implement the IEquatable<T> interface. But if you have a set of related base/child classes that share a common Equality check functionality, you need to create just one IEqualityComparer<T> where T is the Base type and use it with all other types.

public abstract class Star
    {
        public int Age { get; set; }
        public int GamesPlayed { get; set; }
        public int PointsScored { get; set; }
    }

    public class FootballStar : Star
    {
       
    }

    public class BaseballStar : Star
    {

    }

    //This comparer can be used by all instances of type Star 
    public class StarComparer: IEqualityComparer<Star>
    {
        //strongly typed input parameter
        public bool Equals(Star input1, Star input2)
        {
            if (input1.GamesPlayed == input2.GamesPlayed && 
                  input1.PointsScored == input2.PointsScored) 
               return true;
            return false;
        }
        
        public int GetHashCode(Star input)
        {
            //the XOR value
            return input.GamesPlayed ^ input.PointsScored;
        }
    }

    //calling code
    class Program
    {
        static void Main(string[] args)
        {
     FootballStar Brady = new FootballStar() 
                   { Age = 35, GamesPlayed = 900, PointsScored = 55000 };
            FootballStar Peyton = new FootballStar() 
                   { Age = 35, GamesPlayed = 500, PointsScored = 30000 };
            FootballStar Rodgers = new FootballStar() 
                   { Age = 28, GamesPlayed = 500, PointsScored = 31000 };
            FootballStar Griffin = new FootballStar() 
                   { Age = 28, GamesPlayed = 400, PointsScored = 20000 };

            List FootballStars = new List() 
                   {Brady, Peyton, Rodgers, Griffin};
            
            FootballStar Peyton2 = new FootballStar() 
                  { Age = 35, GamesPlayed = 500, PointsScored = 30000 };

            /* the Equals method of the comparer will be used to 
                  determine the equality
               */
    Console.WriteLine(FootballStars.Contains(Peyton2,new StarComparer()));

            /* Add internally calls GetHashCode of the StarComparer 
                  and will not let you add two keys with the same HashCode
               */
         Dictionary StarDictionary = new Dictionary(3,new StarComparer());
            StarDictionary.Add(Brady, "Patriots");
            StarDictionary.Add(Peyton, "Denver");
            StarDictionary.Add(Rodgers, "Greenbay");
            StarDictionary.Add(Griffin, "Washington");

            //Contains and ContainsKey will both internally call 
            //comparer's Equals and GetHashCode methods
            Console.WriteLine(StarDictionary.ContainsKey(Peyton2));
   Console.WriteLine(StarDictionary.Contains(new KeyValuePair(Peyton2, "Denver")));
 }
}
NOTE:
Since the type T of the comparer is of type Star, any types that derive from it can use the same equality comparer as long as they wish to use the same criteria for determining equality. e.g. if the instances of the type BaseballStar were used in a collection, we can use the same EqualityComparer to test for Equality since BaseballStar inherits from Star

.NET interfaces Part 2

IEquatable<T>

 public interface IEquatable<t>
 {       
   bool Equals(T other);
 }
When to use it:
Let us say you have a custom Type and you plan to use instances of that type in a collection. If you want to use methods like List<T>.contains or List<T>.IndexOf you will need to way to check if an item in your collection equals the item we are trying to find.To facilitate this your custom Type needs to implement the Equals method of IEquatable<T>.

NOTE: Since we are checking for equality, we need to override the default implementations of Object.Equals and Object.GetHashCode methods so that they are consistent with the IEquatable<T>.Equals method.

 public class BasketballStar : IEquatable<BasketballStar>
 {
 public int Age { get; set; }
 public int GamesPlayed { get; set; }
 public int PointsScored { get; set; }

     //The IEquatable's Equals method with a strongly typed 
     //input parameter
     public bool Equals(BasketballStar input)
     {
      if(this.GamesPlayed==input.GamesPlayed && 
         this.PointsScored==input.PointsScored) 
        return true;
      return false;
     }

       //overriding the base Equals to keep consistency with the 
       //Equatable's Equals
 public override bool Equals(object input)
 {
    BasketballStar objStar = input as BasketballStar;
    if (objStar == null) return false;
    return this.Equals(objStar);
 }

 /*
         override the base GetHashCode to be consistent with the 
         Equals methods Since we are basing equality based on games
         played and point scored, the hash code is also an XOR of 
         the same properties. So if two objects are equal, the Equals 
         method must return true and thier GetHashCode values must 
         be the same
        */
 public override int GetHashCode()
 {
    //the XOR value
    return this.GamesPlayed ^ this.PointsScored;
 }
 }

//calling code
class Program
{
   static void Main(string[] args)
   {
     BasketballStar Jordan = new BasketballStar() 
                   { Age = 50, GamesPlayed = 900, PointsScored = 55000 };
     BasketballStar Kobe = new BasketballStar() 
                   {Age = 35, GamesPlayed = 500, PointsScored = 30000};
     BasketballStar Lebron = new BasketballStar() 
                   { Age = 28, GamesPlayed = 500, PointsScored = 31000 };
     BasketballStar Durant = new BasketballStar() 
                   { Age = 28, GamesPlayed = 400, PointsScored = 20000 };
     BasketballStar Jordan2 = new BasketballStar() 
                   { Age = 50, GamesPlayed = 900, PointsScored = 55000 };

    //using a list
   List lstStars = new List();
   lstStars.Add(Jordan);
   lstStars.Add(Kobe);
   lstStars.Add(Lebron);
   lstStars.Add(Durant);

   //contains method internally calls the Equals 
          //method of IEquatable
   Console.WriteLine(lstStars.Contains(Jordan2));

   //using a dictionary
   Dictionary StarsDictionary = new Dictionary(3);

   //Add internally calls GetHashCode and will not let you add two 
          //keys with the same HashCode
   StarsDictionary.Add(Jordan, "Chicago Bulls");
   StarsDictionary.Add(Kobe, "Lakers");
   StarsDictionary.Add(Lebron, "Miami");
   StarsDictionary.Add(Durant, "Oklahoma");

   //the contains and containsKey methods both internally call the 
          //GetHashCode as well as the IEquatable's Equals method
   //so both of them need to return consistent values
   Console.WriteLine(StarsDictionary.ContainsKey(Jordan2));
   Console.WriteLine(StarsDictionary.Contains(new KeyValuePair(Jordan2, "chicago bulls")));
 }
}

3/5/13

.NET interfaces - Part 1

I was re-reading some .net basics a couple of weeks ago just to refresh my memory and I came across some core interfaces that I had used in the past.

At that time i was not blogging and hadn't had a chance to write any posts about them. So I was thinking now is probably a good time to do it.

IComparable<T>


public interface IComparable<in T>
{       
  int CompareTo(T other);
}
When to use it:
Let us say you have a custom Type and you plan to use instances of that type in a collection. Whenever you are dealing with collections one of the obvious requirements is that the items in the collection be sortable.To facilitate this your custom Type needs to implement the CompareTo method of IComparable.

Code is as follows:

public class Texas : IComparable
{
        public string Name { get; set; }
        public int Population { get; set; }

/*
This method compares the population of the current instance with the input instance.
returns 0 if they are equal, 1 if this instance's population is greater than the input's population
and -1 if this instance's population is less than the input's population
*/
public int CompareTo(Texas input)
{
   if (this.Population < input.Population) return -1;
   if (this.Population == input.Population) return 0;
   return 1;
} 
}

//calling code

class Program
{

 static void Main(string[] args)
 {

  List lstTexas = new List();

  lstTexas.Add(new Texas() {Name = "Austin", Population = 500});
  lstTexas.Add(new Texas() {Name = "Houston", Population = 1500});
  lstTexas.Add(new Texas() {Name = "Dallas", Population = 900});
  lstTexas.Add(new Texas() {Name = "San Antonio", Population = 1200});
  lstTexas.Add(new Texas() {Name = "Waco", Population = 200});

  /*
     Sort internally calls the CompareTo method.The CompareTo method is 
     usually not called explicitly but is called from methods
     like the List<T>.Sort or Add(in a sorted list)
  */
   lstTexas.Sort();

  foreach (Texas city in lstTexas)
   Console.WriteLine(city.Name);

 }

}


//output - the cities are sorted in the ascending order of their populations
Waco
Austin
Dallas
San Antonio
Houston

NOTE: When you call Sort() with no arguments, you can only sort in ascending order OR descending order depending on your logic inside the CompareTo method. If you wish you can specify a sort order by using the overload of Sort that takes a Comparision delegate as an argument.

12/31/12

Mobile site development - basic points to remember

A mobile site is a powerful mechanism to reach out to millions and billions of users. Though there are similarities with a desktop site, the development of a mobile site is significantly different from a desktop site and comes with a lot of unique challenges and frustrations. Following are some of the points to keep in mind:
  • mobile site audience
    • The mobile user is most likely on the move and accesses the site via small mobile devices
    • The user's patience is limited by the fact that the devices have a limited real-estate and a slower connection compared to a desktop site.
    • The user is expecting to see a simple and intuitive site with easy access to all the important areas of the site.
    • The user will not appreciate or tolerate any unnecessary complexity or slowness on the site.
    • A lot of companies offer mobile versions of their desktop sites and the user has multiple alternatives if the user is not happy with your mobile site
  • mobile devices
    • The real-estate on the mobile devices is limited
    • The devices are not connected to a local access point but work via cellular networks. 
    • The devices run on different mobile operating systems and each operating system comes with its own browser and associated quirks.
    • The device is also a phone, a music player, a video player and much more than just a browser.
  • mobile site look and feel
    • If you are developing a mobile version of a desktop site, the mobile interface needs to be consistent with the desktop site. Though the colors and themes do not have to be exactly the same, there should be an element of familiarity with the desktop version. The users must feel that they are experiencing a concise version of the desktop site.
    • If you are developing a mobile version of a desktop site, the mobile site should behave the same way as the desktop i.e users must experience similar results when they take similar actions on both versions.  
  • mobile site development and testing
    • Mobile sites need to work on mobile devices that run on different operating systems like ios, android,windows and blackberry. This can lead to behavioral quirks and can cause development and testing headaches. This additional complexity must be kept in mind while scoping the time for mobile tasks. 
    •  If you are developing a mobile version of an existing desktop site , it is very likely that you are sharing class libraries between both the versions. Great caution must be taken to ensure that the common libraries are not tampered with in an undesired manner. We need to pay attention to the versioning of the libraries and regression issues every time we make any changes to the common libraries. If any changes are made, care must be taken to do regression testing on both the mobile and site versions. 
  •  mobile network issues
    •  Since the mobile devices are well - mobile, all the communication is wireless and happens through cellular towers that are provided by the cell providers like verizon and sprint. As a result the network speed is limited and there is bound to be some latency involved. It would be wise to reduce the number of requests between the client and server. 
    • Mvc 4 has a concept called bundling that allows us to bundle multiple javascript/css files required on a page and cuts down the number of requests made to the server. Custom bundling also reduces the size of the js/css files.


11/26/12

Chain of responsibility design pattern


The Chain of Responsibility design pattern states:

"Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it. '

I had an opportunity to implement a slight variation of this pattern on one of my recent coding assignments. The requirements for the task were as follows:

There are two partner sites - Site A and Site B. A user on Site A can become a member of Site B by simply clicking on a link. As soon as the user clicks the link on Site A, the site creates an object that encapsulates all the user's information and passes it on to the code on Site B. The users on both the sites share some common attributes and the code on Site B knows how to retrieve the various attributes from that object and map them to the corresponding attributes on Site B. The end goal is to migrate all the Site A user's information into Site B without the user having to fill out all that information on Site B once again.

Based on the requirements above it felt like a good idea to use the Chain of Responsibility pattern. The incoming object from Site A encapsulates different sets of attributes like the user's personal details, professional details, user's hobbies and interests and other such data. So we had this one big request or object that had to be mapped into multiple different entities on the receiving site. This meant that we had to have multiple handlers(classes) on the receiving side each of which knows how to handle the incoming object and map a certain set of the user's attributes.for e.g. we have a class called PersonalInfoMapper that knows how to map the user's personal details from Site A to Site B. We have a class called ProfessionalInfoMapper that knows how to map the user's professional details and so on.

So we implemented the pattern by developing a set of classes that know how to handle the incoming object. The first class in the flow is provided with the incoming object. It maps the data that it can and passes it on to the next class in line. By the end of the chain of classes, all the data for the user from Site A will have been mapped to the corresponding data on Site B. The code stubs for the pattern are as follows:



//The base classes of all the handlers in the Chain of Responsibility

public abstract class MapperBase
{
 protected MapperBase NextHandler;
 public abstract void Execute(MyType siteAObject);
}

public abstract class MapperBase<T>:MapperBase
{  
 public abstract T MapToModel(MyType siteAObject);
 public abstract void Save(T siteBObject);
 public override void Execute(MyType siteAObject)
        {
   //map the incoming data into a custom object
   var siteBModel = MapToModel(siteAObject);
 
          //save the mapped data
            Save(siteBModel);
 
          //if there is a next handler,continue processing
            if (NextHandler != null)
               NextHandler.Execute(siteAObject);            
        }
}


//The first handler in the Chain
public class PersonalInfoMapper : MapperBase<PersonalInfoModel>
{
 public PersonalInfoMapper(ProfessionalInfoMapper nextHandler)
        {
            NextHandler = nextHandler;
 }
  
       public override PersonalInfoModel MapToModel(MyType siteAObject)
        {
   //map data and return mapped object of type PersonalInfoModel   
 }
  
 public override void Save(PersonalInfoModel model)
        {
  //save data
 }
}


//The Next handler in the Chain
public class ProfessionalInfoMapper : MapperBase<ProfessionalInfoModel>
{
 public ProfessionalInfoMapper(InterestsInfoMapper nextHandler)
        {
            NextHandler = nextHandler;
 }
  
 public override ProfessionalInfoModel MapToModel(MyType siteAObject)
        {
  //map data and return mapped object of type ProfessionalInfoModel   
 }
  
 public override void Save(ProfessionalInfoModel model)
        {
   //save data
 }
}


//The Last handler in the Chain
public class InterestsInfoMapper : MapperBase<InterestsInfoModel>
{
 public InterestsInfoMapper()
        {
            NextHandler = null; //no more handlers in the chain
 }
  
 public override InterestsInfoModel MapToModel(MyType siteAObject)
        {
   //map data and return mapped object of type InterestsInfoModel   
 }
  
 public override void Save(InterestsInfoModel model)
        {
   //save data
 }
}

//Calling Code. The types are being instantiated via unity dependency injection
/* 
   The first handler executes, and if it has a next handler specified it triggers the next handler passing the incoming object to it. This process
   continues until there are no more handlers in the chain
*/
public class CallingCodeClass
{
  [Dependency]
  public PersonalInfoHandler FirstHandler {get;set;}

  public void CallingMethod()
  {
 FirstHandler.Execute();
  }
}