Static vs. Singleton

During my daily business I see in nearly every application static classes and/or singletons. And in most cases it looks like they are chosen randomly because if I ask the developer why he has used a static or a singleton then often I don’t get a clear substantiation.

Therefore, within this article, I want to show you the difference between static classes and singletons. This will allow you to do the right choice in your own project and select the variant which fulfills your needs.

 
Purpose

Why do we use singletons or static classes? I think their common use is to provide some utility functions, service methods or constant values. If you look in some articles you will find recommendations like: Static classes should be used to manage constants values like application settings and to implement basis helper libraries for example math libraries. Singletons instead should be used to implement a single access to a resource, e.g. the access to a file which is used to store some application data.

These are proper recommendations but they are only focused on the purpose of the class. What if we look at some other facets like testability, exchangeability, maintainability or in general: usability?

 
Usability

Let us have another look at the example that we want to implement a class which provides some application settings as constant values. It may be implemented by a class providing some static constant properties. So this use case is perfect for a static class. Or isn’t it? What if we want to use different settings in our development, test and productive environments? In this case a static class is not a good choice.

Or think about another example: we want to implement a generic file serialization class. This class should provide some helper functions to serialize and de-serialize objects to and from files. So this also sounds like a good use case for a static class with some static functions. But as soon as we think about testability we will see some disadvantages. If we use this serialization functions in some kind of manager class then we may want to test the manager class independent and write a mocker for the serialization class. But this is not possible if we use a static class.

Based on these examples we can see that there are several decision criteria if we want to select between static classes and singletons. But before we start a deeper analysis of the two concepts we want to look at their implementation.

 
Implementation

A static class is one that has only static methods and static properties. So the methods are more like functions and the design style in a static class is purely procedural. The following code shows an easy example.

static class MyStaticClass
{
    public static void DoSomething()
    {
    }

    public static readonly double MyConstantValue = 3.14;
}

 

A singleton, on the other hand, is a pattern specific for the object oriented design. An instance of an object will be created, with a creation procedure that ensures that there is only ever one instance of that class. The following code shows the example from above, implemented with the standard singleton template.

public class MySingleton
{
    private MySingleton()
    {

    }

    public static MySingleton Instance
    {
        get { return _instance; }
    }

    private static MySingleton _instance = new MySingleton();

    public void DoSomething()
    {
    }

    public readonly double MyConstantValue = 3.14;
}

 

Both classes, the static one and the singleton, can be used in nearly the same way. For the singleton you have to use the instance property to access the class functions and properties.

double x = MyStaticClass.MyConstantValue;
MyStaticClass.DoSomething();

double y = MySingleton.Instance.MyConstantValue;
MySingleton.Instance.DoSomething();       

 
Comparison

So far, we have seen some similarity between static classes and singletons and also some differences. Let us now look into some details and compare the two implementation principles.

A singleton allows access to a single created instance. This instance can be passed as a parameter to other methods. Furthermore a singleton can implement interfaces. This will give as a higher flexibility in terms of abstraction. If a static class is used, you always have to use the concrete instance of the class. A singleton instead allows us to use an abstract interface instead of the concrete implementation.

A singleton can be handled polymorphic without forcing the developer to assume that there is only one instance. So it is used like any other class because the user can see it as a black box and only has to know the interface and not the technical details of the class.

A singleton can be initialized lazily or asynchronously while a static class is generally initialized when it is first loaded. But this is more a technical aspect which is not important in the most projects.

A singleton can be exchanged by another class which implements the same interface. Wherever you pass a singleton as a parameter you can instead substitute it by a mocked or stubbed version.

A singleton can be serialized easily, which may be necessary if you need to save its state or send it remotely to another process.

In summary, most differences between static classes and singletons are good to know from a technical point of view but they are not essential to the project. In my opinion the only crucial fact is, singletons are handled like normal classes. They can implement interfaces, which has a huge impact on the quality of the source code. By using static classes it is not possible to implement according to the SOLID principles.

 
SOLID principles

One of the solid principles is the dependency-inversion-principle. According to this principle, high-level modules should not depend on low level modules. Both should depend on abstractions. This might be implemented by using interfaces. But static classes don’t support interfaces. So, if a static class is used, the high level module depends on the concrete implementation of the low level module and therefore this solid principle is violated

 
Summary

If you are not totally sure whether to use a static class or a singleton, then use a singleton. Singleton classes have nearly no disadvantage compared with static classes or only disadvantages which are not relevant in most projects. Therefore, I would only use static classes for holding utility methods, and using singletons for everything else.

Werbung
Dieser Beitrag wurde unter .NET, C# veröffentlicht. Setze ein Lesezeichen auf den Permalink.

Kommentar verfassen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit deinem WordPress.com-Konto. Abmelden /  Ändern )

Facebook-Foto

Du kommentierst mit deinem Facebook-Konto. Abmelden /  Ändern )

Verbinde mit %s