The Singleton: Pros and Cons
This post is a cross-post from www.ModernesCpp.com.
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:
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.
{loadmoduleid 157}
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
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?[email protected], 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.
?
{loadmoduleid 153}