The Singleton: Pros and Cons

Contents[Show]

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.

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

 

Rainer D 6 P2 540x540Modernes C++ Mentoring

Stay informed about my mentoring programs. Subscribe for the news.

 

 

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 This email address is being protected from spambots. You need JavaScript enabled to view it., 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, Marko, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Evangelos Denaxas, 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, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, and Phillip Diekmann.

 

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

 

 

My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small

 

My special thanks to PVS-Studio PVC Logo

 

Seminars

I'm happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

Bookable (Online)

German

Standard Seminars (English/German)

Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

New

Contact Me

Modernes C++,

RainerGrimmDunkelBlauSmall

Mentoring

Stay Informed about my Mentoring

 

English Books

Course: Modern C++ Concurrency in Practice

Course: C++ Standard Library including C++14 & C++17

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Interactive Course: The All-in-One Guide to C++20

Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code

Visitors

Today 6320

Yesterday 6484

Week 12804

Month 33551

All 10955012

Currently are 146 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments