Singleton Pattern

Yesterday I was viewing a video (Spanish) that explains about how to implement the Singleton pattern in .NET. After some implementations the video ends up showing the best way to have a thread safe implementation of the singleton pattern.

The problem is the video ends saying that the next two implementations are exactly the same on a functional level, which is not completely true.

Implementation 1

   1:  public sealed class Singleton1
   2:  {
   3:      private DateTime creationTime;
   4:      private static Singleton1 instance = null;
   5:      private static object synchro = new object();
   6:   
   7:      private Singleton1()
   8:      {
   9:          creationTime = System.DateTime.Now;
  10:      }
  11:   
  12:      public static Singleton1 Instance
  13:      {
  14:          get
  15:          {
  16:              if (instance == null)
  17:              {
  18:                  lock (synchro)
  19:                  {
  20:                      if (instance == null)
  21:                      {
  22:                          instance = new Singleton1();
  23:                      }
  24:                  }
  25:              }
  26:   
  27:              return instance;
  28:          }
  29:      }
  30:   
  31:      public string CreationTime
  32:      {
  33:          get
  34:          {
  35:              return creationTime.ToString("hh:mm:ss.ffffff");
  36:          }
  37:      }
  38:  }

Implementation 2

   1:  public sealed class Singleton2
   2:  {
   3:      private DateTime creationTime;
   4:      private static Singleton2 instance = new Singleton2();
   5:      
   6:   
   7:      private Singleton2()
   8:      {
   9:          creationTime = System.DateTime.Now;
  10:      }
  11:   
  12:      public static Singleton2 Instance
  13:      {
  14:          get
  15:          {
  16:              return instance;
  17:          }
  18:      }
  19:   
  20:      public string CreationTime
  21:      {
  22:          get
  23:          {
  24:              return creationTime.ToString("hh:mm:ss.ffffff");
  25:          }
  26:      }
  27:  }

The second implementation is correct, since it shows how you can avoid the lock while creating the object instance of the Singleton class. The reason why this is thread safe is because .NET guarantees that the Type Constructor (or Type Initializer on the ECMA standard) is executed only once per AppDomain and is thread-safe.

Regardless both of them are thread-safe, the difference is that the first one is lazy loaded while the second one is eager loaded. In order to implement the singleton pattern using a lazy loaded version and still take profit of the Type Constructors, you need to add a container for the object instance of Singleton2. Doing this the Type Constructor will only be initialized when you access the property (or any other member making reference to it). Below you can see the correct implementation for it.

   1:  public sealed class LazyLoading
   2:  {
   3:      private DateTime creationTime;
   4:   
   5:      private LazyLoading()
   6:      {
   7:          creationTime = DateTime.Now;
   8:      }
   9:   
  10:      public static LazyLoading Instance
  11:      {
  12:          get
  13:          {
  14:              return SingletonContainer.instance;
  15:          }
  16:      }
  17:   
  18:      public string CreationTime
  19:      {
  20:          get
  21:          {
  22:              return creationTime.ToString("hh:mm:ss.ffffff");
  23:          }
  24:      }
  25:   
  26:      class SingletonContainer
  27:      {
  28:          internal static readonly LazyLoading instance = 
  29:              new LazyLoading();
  30:      }
  31:  }

The Importance of Being Earnest

I was commenting with friends some mistakes I found while reviewing the book Pro LINQ Object Relational Mapping with C# 2008. Despite the error's importance, it would be better that they do not appear in the book, moreover when the book must pass a technical review before be printed. i.e.

There is a paragraph that says “...one of the new features in .NET 3.0: the var keyword....” This is incorrect, the var keyword (in the context is used) does not appear in .NET 3.0, but in .NET 3.5 with the implicitly typed local variables and has a different syntax in other languages like VB. Therefore a more accurate affirmation could be “...one of the new features in C# 3.0: the var keyword....”.

Or “...the CLR is doing the heavy lifting for you by translating your queries into method calls...”. This is also incorrect since the Common Language Runtime (CLR) does not translate the LINQ queries into methods; instead each language compiler is in charge of that conversion, something that you can easily see by checking the IL and metadata generated by the compiler. This error is a bit more serious, because the reader can think it is better to use the method syntax instead of the LINQ syntax to avoid the translation performance cost during runtime, when it is not the case.

Anyway, the controversy came out when I said the author talks in the Entity Framework chapter about "Single-Table Mapping", regardless if the term is correct or not, the expression used in EF is a different one: Table-per-hierarchy. I think the author should have utilized the same term as in EF documentation. Names are very important to recognize the concepts behind them and the best is that within a context everybody uses the same, in this case the context was Entity Framework.

In my business area, credit card processing, we are sick to see how acquiring banks and payment processors use the same term for different things. i.e. Void, Reversal, Cancellation can be exactly the same operation or a totally different one depending on the company using the term, which can cause lot of confusion until you do not agree a nomenclature. Tables, views, methods, variables, classes ... none of them are an exception when you need to decide a good term. But IT world is not the only place where having the right name can help you to success, just remind the Oscar Wilde's play "The Importance of Being Earnest".  

Therefore, next time you need to select a name try to invest time enough deciding a good one that is descriptive enough, it would be better than having to waste it later on checking the documentation to remember what the term intended to mean.

The curse of copy paste

Today I want to write about the most powerful development tool of our days: the copy paste.

Copy paste helps you to develop faster, increases a lot your productivity, you can develop business components, forms, entire applications; you can develop code even before you understand what it does … all just in minutes!! Your boss is happy, your customer even more and that’s great … but what happens when the original code has a bug? Then all the copy pasted components, forms, applications we did in minutes’ trend to have the same bug and now you need to fix it everywhere, the amount of bugs grows at lightspeed. But, hey!! doesn’t matter, why don’t we use copy paste again to patch everywhere? … Sorry, you are done, once you have started with this development style, there is no return back, you are damned by the “the curse of the copy paste”. Hereinafter you are damned to find the same comments, bugs, even wrongly typed method and variable names … everywhere

Don’t you believe me? Do a review or try to download tools like Simian and use them inside one of the projects of your clients, of course you will not find anything in your own projects, won’t you? Better don’t try.

Maybe it can make you feel better knowing that software like … mmm I’m not going to say the name because I want to be politically correct (tip: it’s a widely used tool to rapidly build web sites with forums, blogs and photos). If you already know which software I’m talking about, try to search “blog” in the project supposed to contain code for photos: 30 matching lines. This deserves a bigger “wow” than the 3D Vista windows; “at least” most of them are comments.

Next time after copy and before paste, please just stop for a second and try to think if you can refactor your classes … lot of times copy paste development is synonym of a bad design.

Of course we can also sum our efforts and ask Microsoft to remove the copy paste functionality from all versions of Visual Studio.

Back to the University

Past week, I was speaking with a guy who just started his first year at Computer Science, he explained me the task he needs to do and I felt some nostalgia about those days when you should try to solve "impossible" algorithms, learning everyday new development techniques ... mmm that doesn't sound that different than nowadays ... anyway ...

I found funny to come back to the University and I decided to try it myself, I took a paper and a pen and I wrote the pseudocode. Believe me if I say that I asked the guy to keep me informed about all his assignments, it was funnier than doing a sudoku. 

The idea is to draw a symmetric rhombus using ASCII chars, each concentric rhombus must be drawn using a different ASCII char. Next you can see a C# version of it, they use Modula-2 as programming language, so I didn't use any fancy .net features.

   1: class Program
   2: {
   3:    const int startingAsciiCode = 32;
   4:    const int maxSize = 40;
   5:    static void Main(string[] args)
   6:    {
   7:       while (true)
   8:       {
   9:          Console.Clear();
  10:          Console.WriteLine("Please insert the size: (ctrl + c to exit)");
  11:          string size = Console.ReadLine();
  12:          int parsedSize;
  13:          if (!int.TryParse(size, out parsedSize) || (parsedSize < 2 || parsedSize > 94))
  14:          {
  15:             Console.WriteLine("Please introduce a valid integer value between 2 and 94");
  16:             Console.ReadKey();
  17:          }
  18:          else
  19:          {
  20:             Console.Clear(); 
  21:             
  22:             // we calculate the diagonal size
  23:             int diagonal = (parsedSize * 2) - 1;
  24:             int charsToDraw = 1;
  25:             // Iterate all the rows
  26:             for (int row = 1; row <= diagonal; row++)
  27:             {
  28:                // Calculate the blank spaces and the total amount of chars to draw
  29:                int blankSpaces = (int)((diagonal - charsToDraw) / 2);
  30:                int totalSize = blankSpaces + charsToDraw; 
  31:                
  32:                // Iterate the columns
  33:                for (int i = 1; i <= totalSize; i++)
  34:                {
  35:                   if (i < blankSpaces)
  36:                   {
  37:                      // Draw blank spaces
  38:                      Console.Write(' ');
  39:                   }
  40:                   else
  41:                   {
  42:                      // Draw non blank chars
  43:                      // We use a different char for each concentric rhombus
  44:                      int asciiOffset;
  45:                      if (i <= parsedSize)
  46:                      {
  47:                         asciiOffset = i - blankSpaces;
  48:                      }
  49:                      else
  50:                      {
  51:                         asciiOffset = (totalSize + 1) - i;
  52:                      }
  53:                      Console.Write((Char)(startingAsciiCode + asciiOffset));
  54:                   }
  55:                }
  56:                Console.WriteLine();
  57:                if (row < parsedSize)
  58:                {
  59:                   charsToDraw = charsToDraw + 2;
  60:                }
  61:                else
  62:                {
  63:                   charsToDraw = charsToDraw - 2;
  64:                }
  65:             }
  66:             Console.WriteLine();
  67:             Console.WriteLine("Press a key to continue");
  68:             Console.ReadKey();
  69:          }
  70:       }
  71:    }
  72: }