Singleton’s implemented the right way

The Singleton pattern implementation out of the gang of four book [Gamma, Helm, Johnson, and Vlissides. Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley, 1995.] is not thread save (at least in C# it isn’t). Besides that it uses a GetInstance() method and makes not use of C# properties. I think a simple Instance property is nicer and follows the general C# style.

Check out my version of a Singleton implemenation:

public class Singleton 

{ 

    private readonly static Singleton singleton = new Singleton(); 

    public static Singleton Instance() 

    { 

        return singleton; 

    } 

    private Singleton() 

    { 

    } 

}

Upsides of this approach are that it is thread save and look quite simple. Downside is you don’t have exact control over when the Instance is created. In the few cases where this is important (Let’s say the creation of the instance is very time consuming and you want to guarantee that it is only created when needed you might want to check out the double-check locking approach more detailed explained here: http://msdn2.microsoft.com/en-us/library/ms998558.aspx.

The double-check locking approach is also a solution if you need to do some extra stuff when you create the one instance.

Why are decimals a good idea?

It’s easy: always use decimals for variables that represent money.

Reason to avoid floats or doubles: They will produce incorrect results when you try to calculate something. I have to add, it will produce errors in very rare cases. However you can avoid it by using decimals!

You don’t believe me? Try this: 77.1 * 850 should be exactly 65,535.

decimal correct = (decimal)77.1 * (decimal)850d;

correct will be = 65535

double incorrect = (double)77.1 * (double)850;

incorrect will be = 65534.999999999993

Why is that? That’s because 0.1 has no exact representation in binary… it’s a repeating binary number. It’s sort of like how 1/3 has no representation in decimal. 1/3 is 0.33333333 and you have to keep writing 3’s forever. If you lose patience, you get something inexact.

So what are the downsides to decimal?

  1. They use a lot more space, 128 bit to be exact. But who cares these days…
  2. They are slow as a dog. Again, doesn’t matter if you are not about to program your own spreadsheet application.