{"id":6451,"date":"2022-09-25T14:42:54","date_gmt":"2022-09-25T14:42:54","guid":{"rendered":"https:\/\/www.modernescpp.com\/index.php\/singleton-pros-and-cons\/"},"modified":"2023-06-26T08:59:08","modified_gmt":"2023-06-26T08:59:08","slug":"singleton-pros-and-cons","status":"publish","type":"post","link":"https:\/\/www.modernescpp.com\/index.php\/singleton-pros-and-cons\/","title":{"rendered":"The Singleton: Pros and Cons"},"content":{"rendered":"<p>I introduced in my last post <a href=\"https:\/\/www.modernescpp.com\/index.php\/creational-patterns-singleton\">&#8220;The Singleton<\/a>&#8220;, 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.<\/p>\n<p><!--more--><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-6435\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/09\/CreationalPatterns.png\" alt=\"CreationalPatterns\" width=\"650\" height=\"330\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/09\/CreationalPatterns.png 1220w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/09\/CreationalPatterns-300x152.png 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/09\/CreationalPatterns-1024x520.png 1024w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/09\/CreationalPatterns-768x390.png 768w\" sizes=\"auto, (max-width: 650px) 100vw, 650px\" \/><\/p>\n<p>&nbsp;<\/p>\n<p>First of all, is Singleton a Pattern or an Anti-Pattern?<\/p>\n<h2>Singleton: A Pattern or an Anti-Pattern?<\/h2>\n<p>My most read post so far is my post &#8220;<a href=\"https:\/\/www.modernescpp.com\/index.php\/thread-safe-initialization-of-a-singleton\">Thread-safe Initialization of a Singleton<\/a>&#8220;.&nbsp; It was read more than 300&#8217;000 times, and I got many comments.<\/p>\n<p>Consequentially, I asked the community if they use the Singleton pattern: <a href=\"https:\/\/twitter.com\/rainer_grimm\/status\/699717467770392576\">https:\/\/twitter.com\/rainer_grimm\/status\/699717467770392576<\/a>. About 150 people voted on Twitter, and the answer was not as clear as I expected. 59% use the Singleton, but 41% do not.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-6450\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/09\/singletonPoll.png\" alt=\"singletonPoll\" width=\"500\" height=\"279\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/09\/singletonPoll.png 739w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2022\/09\/singletonPoll-300x168.png 300w\" sizes=\"auto, (max-width: 500px) 100vw, 500px\" \/><\/p>\n<p>The comment I got about the Singleton Pattern can be summed up in two answers:<\/p>\n<ol>\n<li>I don&#8217;t use the Singleton because it is an anti-pattern.<\/li>\n<li>I only use the Singleton deliberately.<\/li>\n<\/ol>\n<p>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.<\/p>\n<p>Therefore, let&#8217;s dive deeper and analyze the pros and cons of the Singleton Pattern.<\/p>\n<\/p>\n<h2>The Advantages and Disadvantages of the Singleton Pattern<\/h2>\n<p>I want to start positive:<\/p>\n<h3>Advantages<\/h3>\n<h4>Global Access Point<\/h4>\n<p>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.<\/p>\n<h4>Unique Entity Model<\/h4>\n<p>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.<\/p>\n<h3>Disadvantages<\/h3>\n<h4>Static Initialization Order Fiasco<\/h4>\n<p>In my last post, &#8220;The Singleton,&#8221; 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 &#8220;<a href=\"https:\/\/en.wikipedia.org\/wiki\/Design_Patterns\">Design Patterns: Elements of Reusable Object-Oriented Software&#8221;<\/a> based implementation of the Singleton Pattern has this issue, but the <a href=\"https:\/\/en.wikipedia.org\/wiki\/Scott_Meyers\">Meyers <\/a>Singleton overcomes it.<\/p>\n<h4>Concurrency<\/h4>\n<p>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.&nbsp;<\/p>\n<h4>Too often used<\/h4>\n<p>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.&nbsp;<\/p>\n<h4>Hidden Dependency<\/h4>\n<p>You may assume it; this is my key point. A Singleton introduces a hidden dependency and breaks, therefore, testability. Let&#8217;s consider the following code snippet:<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #007788; font-weight: bold;\">void<\/span> <span style=\"color: #cc00ff;\">func<\/span>() {\r\n   ...\r\n   DataBase<span style=\"color: #555555;\">::<\/span>getInstance().update(<span style=\"color: #cc3300;\">\"something\"<\/span>);\r\n   ...\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>The call <code>DataBase::getInstance().update(\"something\") <\/code>creates a hidden dependency. The caller of the function <code>func<\/code> 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 <code>func<\/code> and the database.<\/p>\n<p>Unit Tests should<\/p>\n<ul>\n<li>have no external dependency.<\/li>\n<li>be fast.<\/li>\n<li>have no side effects.<\/li>\n<\/ul>\n<p>Honestly, we can not blame the Singleton Pattern for the hidden dependency. This is just bad software design. Let me restructure the code.<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\">func(DataBaseSingleton<span style=\"color: #555555;\">::<\/span>getInstance());\r\n\r\n...\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">void<\/span> func(DataBase<span style=\"color: #555555;\">&amp;<\/span> db) {\r\n   ...\r\n   db.update(<span style=\"color: #cc3300;\">\"something\"<\/span>);\r\n   ...\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Just make the <code>DataBase<\/code> 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?<\/p>\n<p>Make out of DataBase an interface and provide at least two implementations. One is the original Singleton <code>DataBaseSingleton<\/code> and the other is a <a href=\"https:\/\/en.wikipedia.org\/wiki\/Mock_object\">mock object<\/a>: <code>DataBaseMock.<\/code> The <code>DataBaseMock<\/code> mimics the behavior of the <code>DataBaseSingleton<\/code> and can be used as a replacement for the real <code>DataBase<\/code>. The <code>DataBaseMock<\/code> is fully deterministic and introduces no dependency.<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\">func(DataBaseMock<span style=\"color: #555555;\">::<\/span>getInstance());\r\n\r\n...\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">void<\/span> func(DataBase<span style=\"color: #555555;\">&amp;<\/span> db) {\r\n   ...\r\n   db.update(<span style=\"color: #cc3300;\">\"something\"<\/span>);\r\n   ...\r\n}\r\n<\/pre>\n<\/div>\n<h3>My Resume<\/h3>\n<p>I don&#8217;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.<\/p>\n<p>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:<\/p>\n<ul>\n<li>Simplify C++ by Arne Mertz:<a href=\"https:\/\/arne-mertz.de\/2015\/04\/singletons-whats-the-deal\/\"> Singletons: What&#8217;s the Deal? <\/a><\/li>\n<li>Fluent C++ by Jonathan Boccara: <a href=\"https:\/\/www.fluentcpp.com\/2018\/03\/06\/issues-singletons-signals\/\">The Issues With the Singletons and Hot to Fix Them<\/a><\/li>\n<\/ul>\n<h3>Your Resume<\/h3>\n<p>I&#8217;m happy to hear your resume. Please write me an e-mail to&nbsp;<a href=\"mailto:Rainer.Grimm@ModernesCpp.de\">Rainer.Grimm@ModernesCpp.de<\/a>, and I will write an additional post if necessary.<\/p>\n<h2>What&#8217;s Next?<\/h2>\n<p>So far, I haven&#8217;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.<\/p>\n<p>&nbsp;<\/p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>I introduced in my last post &#8220;The Singleton&#8220;, 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.<\/p>\n","protected":false},"author":21,"featured_media":6435,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[379],"tags":[404],"class_list":["post-6451","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-patterns","tag-singleton"],"_links":{"self":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/6451","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/users\/21"}],"replies":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/comments?post=6451"}],"version-history":[{"count":1,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/6451\/revisions"}],"predecessor-version":[{"id":6658,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/6451\/revisions\/6658"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media\/6435"}],"wp:attachment":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media?parent=6451"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/categories?post=6451"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/tags?post=6451"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}