CreationalPatterns

The Singleton: Pros and Cons

I introduced in my last post “The Singleton“, the classical Singleton and the so-called Meyers Singleton. The Singleton Pattern is highly controversial. Let me, therefore, discuss in this post the pros and cons of the Singleton.

CreationalPatterns

 

First of all, is Singleton a Pattern or an Anti-Pattern?

Singleton: A Pattern or an Anti-Pattern?

My most read post so far is my post “Thread-safe Initialization of a Singleton“.  It was read more than 300’000 times, and I got many comments.

Consequentially, I asked the community if they use the Singleton pattern: https://twitter.com/rainer_grimm/status/699717467770392576. About 150 people voted on Twitter, and the answer was not as clear as I expected. 59% use the Singleton, but 41% do not.

singletonPoll

The comment I got about the Singleton Pattern can be summed up in two answers:

  1. I don’t use the Singleton because it is an anti-pattern.
  2. I only use the Singleton deliberately.

However, I think one faction has not spoken up in this discussion. That is the fraction of developers who use the Singleton Pattern frequently. I know this faction from my daily work. If I include this silent fraction in the survey result, I assume that about 80% of the developers use the Singleton Pattern.

Rainer D 6 P2 500x500

 

Rainer D 6 P2 500x500Modernes C++ Mentoring

  • "Fundamentals for C++ Professionals" (open)
  • "Design Patterns and Architectural Patterns with C++" (open)
  • "C++20: Get the Details" (open)
  • "Concurrency with Modern C++" (open)
  • "Generic Programming (Templates) with C++": October 2024
  • "Embedded Programming with Modern C++": October 2024
  • "Clean Code: Best Practices for Modern C++": March 2025
  • Do you want to stay informed: Subscribe.

     

    Therefore, let’s dive deeper and analyze the pros and cons of the Singleton Pattern.

    The Advantages and Disadvantages of the Singleton Pattern

    I want to start positive:

    Advantages

    Global Access Point

    A Singleton is a global object in disguise, but it provides a global access point. As a global, a Singleton can be accessed from anywhere in the program, but it cannot be modified from anywhere. It can only be modified from within the Singleton. It is, therefore, a means to protect globals.

    Unique Entity Model

    It makes it easier to reason about your program when you model entities of reality. In reality, we often have Singletons such as registration offices, global timers, or factories for unique IDs. Consequentially, you achieve a very nice match between the program abstraction and the reality. This correspondence helps you and your client to better understand the program.

    Disadvantages

    Static Initialization Order Fiasco

    In my last post, “The Singleton,” I already wrote about the static initialization order fiasco. It essentially means that you have no guarantee in which order statics in different translation units are initialized and destructed. The “Design Patterns: Elements of Reusable Object-Oriented Software” based implementation of the Singleton Pattern has this issue, but the Meyers Singleton overcomes it.

    Concurrency

    The Meyers Singleton also overcomes the concurrency issue of the classical Singleton implementation. The Meyers Singleton is based on a local static. Since C++98, statics with local scope are lazily initialized, and with C++11, even thread-safe. 

    Too often used

    The Singleton Pattern was often used when it was inappropriate, and a simple class instance could do a better job. This was mainly due to the fact that software developers want to prove that they understood the classical design pattern, and the Singleton often seems to be the long-hanging fruit. Honestly, we can not blame the Singleton Pattern for its misuse. 

    Hidden Dependency

    You may assume it; this is my key point. A Singleton introduces a hidden dependency and breaks, therefore, testability. Let’s consider the following code snippet:

    void func() {
       ...
       DataBase::getInstance().update("something");
       ...
    }
    

     

    The call DataBase::getInstance().update("something") creates a hidden dependency. The caller of the function func has no idea that a database is called internally. What are the consequences? The code is no unit anymore and, therefore, not unit-testable. You cannot test this code in isolation. You can only make a system test including the operational database. You always end with two tests. You test the code of the function func and the database.

    Unit Tests should

    • have no external dependency.
    • be fast.
    • have no side effects.

    Honestly, we can not blame the Singleton Pattern for the hidden dependency. This is just bad software design. Let me restructure the code.

    func(DataBaseSingleton::getInstance());
    
    ...
    
    void func(DataBase& db) {
       ...
       db.update("something");
       ...
    }
    

     

    Just make the DataBase part of the interface of the function. Now, there is no hidden dependency anymore. The function can be fast and without side effects. Now, it is a unit and, therefore, unit testable. Why?

    Make out of DataBase an interface and provide at least two implementations. One is the original Singleton DataBaseSingleton and the other is a mock object: DataBaseMock. The DataBaseMock mimics the behavior of the DataBaseSingleton and can be used as a replacement for the real DataBase. The DataBaseMock is fully deterministic and introduces no dependency.

    func(DataBaseMock::getInstance());
    
    ...
    
    void func(DataBase& db) {
       ...
       db.update("something");
       ...
    }
    

    My Resume

    I don’t want to argue for or against the Singleton Pattern. Each pattern has its drawbacks, and this holds, in particular, true for the Singleton Pattern. Therefore, you should consider whether the advantages outweigh the disadvantages in the concrete case. Additionally, you should use the Meyers Singleton and make the Singleton a component of your function signature.

    To conclude my discussion about the pros and cons of the Singleton, here are two critical posts about the pattern from Arne Mertz and Jonathan Boccara:

    Your Resume

    I’m happy to hear your resume. Please write me an e-mail to Rainer.Grimm@ModernesCpp.de, and I will write an additional post if necessary.

    What’s Next?

    So far, I haven’t written about the singleton pattern alternatives. In my next post, I present two additional patterns: the Monostate Pattern (aka Borg Idiom) and Dependency Injection.

     

    Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Stephen Kelley, Kyle Dean, Tusar Palauri, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, Marco Parri Empoli, Philipp Lenk, Charles-Jianye Chen, Keith Jeffery, Matt Godbolt, and Honey Sukesan.

    Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.

    My special thanks to Embarcadero
    My special thanks to PVS-Studio
    My special thanks to Tipi.build 
    My special thanks to Take Up Code
    My special thanks to SHAVEDYAKS

    Modernes C++ GmbH

    Modernes C++ Mentoring (English)

    Do you want to stay informed about my mentoring programs? Subscribe Here

    Rainer Grimm
    Yalovastraße 20
    72108 Rottenburg

    Mobil: +49 176 5506 5086
    Mail: schulung@ModernesCpp.de
    Mentoring: www.ModernesCpp.org

    Modernes C++ Mentoring,

     

     

    0 replies

    Leave a Reply

    Want to join the discussion?
    Feel free to contribute!

    Leave a Reply

    Your email address will not be published. Required fields are marked *