Make programming easier

Is Singleton pattern really that bad?

Introduction

Łukasz Kużyński

Łukasz Kużyński

Frontend and backend developer with almost 10 year of experience. Passionated about programming, computers and how things work.


Is Singleton pattern really that bad?

Posted by Łukasz Kużyński on .
Featured

Is Singleton pattern really that bad?

Posted by Łukasz Kużyński on .

It's quite common to believe that Singleton is a total antipattern and should be avoided at all cost. Well... that's not always true. The key here is to understand why Singleton is perceived as a bad thing.

Singleton? What is it?

Singleton is a creational design pattern to make sure that only one instance of class exists in the program. Here is the simple example in PHP.

class Foo {  
    private static $instance;

    private function __construct() {}

    public static function getInstance() {
        if (!self::$instance) {
            self::$instance = new Foo();
        }
        return self::$instance;
    }
}

$instance = Foo::getInstance();
$instance2 = Foo::getInstance();

$instance === $instance2; // true

Why is singleton so bad?

People use singleton for different kind of classes like Database, Templates, Routing etc. Basically every usage of singleton is bad if the object contains a mutable state. That causes problems with testing, reusability, hiding dependencies and tight coupling.

Is there any good usage of singleton?

If the object does not contain a mutable state the usage of singleton might be good.
Here are a few examples:

Note that the usages above provides only one benefit: lower memory usage. I highly recommend to read about flyweight pattern that helps sharing small subset of objects (not single instance of one class) in the program instead creating new one every time.

Take home message

Useful and proper usage of singletons is rare but still possible. I mention it since it's very important for programmers not to learn the rules and follow them blindly but understand their origin. Understand what you do and it'll make your work easier.

Łukasz Kużyński

Łukasz Kużyński

Frontend and backend developer with almost 10 year of experience. Passionated about programming, computers and how things work.

View Comments...