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.
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.
The comment I got about the Singleton Pattern can be summed up in two answers:
- I don’t use the Singleton because it is an anti-pattern.
- 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.
The Advantages and Disadvantages of the Singleton Pattern
I want to start positive:
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.
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.
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.
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:
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.
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 mimics the behavior of the
DataBaseSingleton and can be used as a replacement for the real
DataBaseMock is fully deterministic and introduces no dependency.
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:
- Simplify C++ by Arne Mertz: Singletons: What’s the Deal?
- Fluent C++ by Jonathan Boccara: The Issues With the Singletons and Hot to Fix Them
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.
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, Kris Kafka, 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, 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, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, and Bhavith C Achar.
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|
I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
- Embedded Programmierung mit modernem C++ 12.12.2023 – 14.12.2023 (Präsenzschulung, Termingarantie)
Standard Seminars (English/German)
Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.
- C++ – The Core Language
- C++ – The Standard Library
- C++ – Compact
- C++11 and C++14
- Concurrency with Modern C++
- Design Pattern and Architectural Pattern with C++
- Embedded Programming with Modern C++
- Generic Programming (Templates) with C++
- Clean Code with Modern C++
- Phone: +49 7472 917441
- Mobil:: +49 176 5506 5086
- Mail: schulung@ModernesCpp.de
- German Seminar Page: www.ModernesCpp.de
- Mentoring Page: www.ModernesCpp.org
Modernes C++ Mentoring,