<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>jalf.dk &#187; singleton</title>
	<atom:link href="http://jalf.dk/blog/tag/singleton/feed/" rel="self" type="application/rss+xml" />
	<link>http://jalf.dk/blog</link>
	<description>Musings and thoughts on programming and other geeky stuff</description>
	<lastBuildDate>Sat, 07 Jan 2012 15:42:18 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Singletons: Solving problems you didn’t know you never had since 1995</title>
		<link>http://jalf.dk/blog/2010/03/singletons-solving-problems-you-didnt-know-you-never-had-since-1995/</link>
		<comments>http://jalf.dk/blog/2010/03/singletons-solving-problems-you-didnt-know-you-never-had-since-1995/#comments</comments>
		<pubDate>Fri, 12 Mar 2010 04:40:59 +0000</pubDate>
		<dc:creator>jalf</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[singleton]]></category>
		<category><![CDATA[stackoverflow]]></category>

		<guid isPermaLink="false">http://jalf.dk/blog/?p=532</guid>
		<description><![CDATA[Funny how some subjects seem to attract catchy titles like flies. A lot of very clever people have written volumes about “The Simpleton Pattern”, and “Singletonitis” (bah, dead link, let’s use this instead then). Many people are in love with the Singleton pattern. Others — a small minority, I suspect — consider it a mistake, [...]]]></description>
			<content:encoded><![CDATA[<p>Funny how some subjects seem to attract catchy titles like flies. A lot of very clever people have written volumes about <a href="http://steve.yegge.googlepages.com/singleton-considered-stupid">“The Simpleton Pattern”</a>, and <a href="http://www.gamedev.net/community/forums/mod/journal/journal.asp?jn=259115">“Singletonitis”</a> (bah, dead link, let’s use <a href="http://pragmaticintegration.blogspot.com/2006/02/singletonitis.html">this</a> instead then).</p>

<p>Many people are in love with the <a href="http://en.wikipedia.org/wiki/Singleton_pattern">Singleton pattern</a>. Others — a small minority, I suspect — consider it a mistake, an anti-pattern, or something that was only ever included in <em>the</em> Design Patterns book as a lifeline to procedural programmers who couldn’t really figure out this OOP thing.
<span id="more-532"></span></p>

<p>I won’t pretend to be half as clever as all the people who have already written about the problems with singletons years ago, and I don’t think I have anything <em>new</em> to bring to the table. But it is a pattern I learned to loathe years ago. (Singletons do sound attractive when you first hear of them. But they pale a bit when you end up having to tear up and rewrite half your code just because all your singleton classes start revealing their shortcomings) And for a long time now, I’ve tried to convince other programmers that Singletons have some serious problems. Recently, it seems like I’m even getting noticed for it among the users of StackOverflow.</p>

<p>First, <a href="http://stackoverflow.com/users/87234/gman">oneuser</a> posts an answer to <a href="http://stackoverflow.com/questions/2080233/is-it-good-programming-to-have-lots-of-singleton-classes-in-project/2080242#2080242">one question</a>, and I comment with a mild disagreement, and the discussion goes on for a few more comments. As singleton rants go, this one is pretty mild, and I don’t really think about it any further. Then, a few weeks later, I discover his blog and <a href="http://blackninjagames.com/?p=24">this post</a>. Wow! A convert. A person I know to be a smart and a knowledgeable programmer has changed his mind in response to something <em>I</em> said… I’m flattered.</p>

<p>And today, I noticed another question being posted, which had both Boost and Singletons in the title — how could I resist? Two subjects I enjoy talking about, even if the things I say about them are very different. Surprisingly, the comments there already mentioned me, and some of my earlier answers regarding singletons. Should I be flattered or worried that people have started bringing my name up when discussing Singletons?</p>

<p>Anyway, one of the comments also suggested I write a blog post describing my argument in detail. So I will.
I’ll even throw in a redirect link from http://jalf.dk/singleton, to make it as easy as possible to find.</p>

<h1>Two wrongs don’t make a right</h1>

<p>There are a lot of problems with singletons. In fact, it’s surprising that so many people still consider the pattern useful, when it is afflicted with so many weaknesses and flaws. However, for now I will single out the two that I feel are the most fundamental: not just problems with how a singleton works, but with what they’re trying to achieve:</p>

<p>A singleton, as defined by the Gang of Four, combines two properties:</p>

<ul>
<li>it guarantees that exactly one instance of an object exists. While that one instance is typically created lazily, so it doesn’t technically exist throughout the entire application’s lifetime, it always seems to the programmer as if precisely one instance exists, and</li>
<li>it guarantees global access to this one instance.</li>
</ul>

<p>Let’s pick those apart a bit. The last one is easiest: it is, by now, fairly common knowledge that <em>global state is bad</em>. We don’t like global variables, we don’t like static class members, we don’t like anything that makes it harder to isolate bits of our code. Dependence on global state causes a lot of problems: it hurts parallelism, as access to global mutable state generally has to be serialized through the use of locks. It makes dependencies harder to detect and control (any function might silently decide to access our singleton. The function signature says nothing about this, so we have to read the source code of the function to determine if this is the case. And because it is so convenient to always just add a reference to a singleton, we tend to do it a lot. When you have a singleton, you quickly end up in a situation where three out of four classes depend on it. How did that happen? Why, logically speaking, do so many classes need direct access to the database? Or the renderer? Is that good design? Not only is this messy, it’s also painfully hard to fix after the fact. Once we have these dependencies on global objects everywhere, that’s a lot of code we need to change to eliminate the global. Almost every class will be impacted by the change, and a huge number of functions have to have their signatures modified to take that extra parameter replacing the global. Or even worse, the function has to be completely rewritten to eliminate the need for whatever service the singleton provided. The more globals you have in your project, the more your dependency graph starts resembling spaghetti. And the harder it gets to clean it up.</p>

<p>It hurts reusability, as code taken from one project and inserted into another may break because it depended on globals not present in the new project. It hurts testability partly for the same reason, a unit test testing a class must suddenly provide a number of globals as well just for the code under test to compile, but also because global state makes tests less deterministic. One test might change the state of this global, affecting the outcome of the next test to run.</p>

<p>Globals are bad for a lot of reasons. They have their uses, no doubt about that, but we should be suspicious whenever the solution to a problem involves global data. It might be the best solution, but often, it is more trouble than it’s worth.</p>

<p>The other point is more subtle. Why do I object to a class enforcing that “only one instance may exist”? It’s really just common sense. As the Agile movement tells us, we don’t really know what our code is going to look like tomorrow. Over the course of development, we <em>have</em> to adapt to changes, modify our code, revise decisions already made. Why put roadblocks in front of us? Why make it harder to adapt to unforeseen changes or requirements?</p>

<p>Today, I might think that I need only one logger instance. But what if I realize tomorrow that I need two? That’s not so far fetched. We may have one log we write ad-hoc messages intended for debugging purposes, solely to be read by developers, and another formalized log, where structured messages are written when predetermined events occur, so that the application can be monitored in production. Sure, we <em>could</em> define the two as completely separate classes, and then we’d only need one instance of each (but then we’d start duplicating code). Or we could use the same log instance to write to both logs (but then the logging code would become more complex, having to interleave two separate and non-overlapping logs.</p>

<p>Once we’ve accepted that an application may need more than one logger, shouldn’t we do ourselves the favor of ensuring that our loggers <em>can</em> be instantiated more than once, just in case it turns out to be the right thing to do? We’re not even adding any complexity, there’s no cost associated with this. On the contrary, we’re <em>removing</em> significant complexity. Thread-safe singletons are surprisingly hard to get right. Dependencies between singletons are tricky and circular ones can cause them to blow up in all sorts of fun ways. And let’s not even get into how to handle anything our singletons might do while the application is shutting down. What if the database singleton tries to write a simple “goodbye” log message to the log singleton? What if the log singleton got destroyed before the database one? Ouch.</p>

<p>Singletons are hard to write and hard to use. Removing them only simplifies our code, so if it also enables us to better adapt to unforeseen requirements, why <em>shouldn’t</em> we remove them?</p>

<p>Not convinced? Let’s think of some other examples then:</p>

<ul>
<li><em>the application configuration should be a singleton, right? We <strong>obviously</strong> can’t have more than one of those!</em> Wrong. We can. We often do. Think about what happens when the user opens the “Options” screen and modifies the settings. During that time, two sets of settings exist: the “applied” settings that are currently in effect, and the “speculative” ones, currently being picked out by the user. Once he clicks OK, the speculative changes should be applied, replacing the ones that were previously in effect. But until then, we have two sets of settings to maintain.</li>
<li><em>a database connection pool then! If we have more than one pool of connections, we can’t efficiently share them!</em> Correct, but perhaps we don’t <em>want</em> to share them. Perhaps I want to ensure that library A has one pool of 10 connections available to it, component B has a smaller pool of 3 connections, an components C, D and E use the global pool with however many connections it supplies. That would ensure that no matter the number of threads running in component B, it’ll never starve out other components trying to access the database. It can never hold more than three connections, leaving room for other components. Of course, in the common case, we do want all connections to be shared in one single pool. But perhaps not <em>always</em>. So yes, there should probably be a globally accessible default pool available. But why shouldn’t it also be possible to define new <em>local</em> pools if the user deems it necessary? Why limit ourselves to one instance?</li>
</ul>

<p>And even if you do come up with some case where we absolutely <em>must</em> never have more than one instance, where it would make the sky come crashing down on us, consider testing. Consider that each of your unit tests should set up the environment it needs, and run within that environment, in isolation from other tests. That means that every test should create its own logger instance, or database pool instance, or whatever else our singletons are doing, just so it can avoid being polluted by stateful changes made by earlier tests. Each unit test for the Direct3D renderer <em>should</em> set up its own renderer object. Each physics simulation test <em>should</em> initialize the physics engine first, and shut it down again after use. Singletons don’t easily allow that. Sure, we can extend them with explicit <code>Create()</code> and <code>Destroy()</code> methods, but then our abstraction is starting to get leaky. We can no longer assume that precisely one instance exists, because we might have just destroyed the one that existed.</p>

<p>The “exactly one instance” guarantee removes flexibility from our code that we may need, in order to enforce a constraint that we <em>definitely</em> don’t need. Where’s the harm in allowing the user to create more than one instance <em>if he decides to?</em></p>

<p>C++ programmers are familiar with <code>std::cout</code>, the standard output stream. Funny thing about this, it is a simple global object. We can <em>obviously</em> never have more than one standard output stream. But we <em>can</em> have more than one stream. The standard library just initializes one of them to point to the standard output, and saves it as a global variable. We don’t need it to be a singleton, we don’t even need it to be a static class specially defined for the purpose. We just need a stream, defined somewhere where it’s globally accessible.</p>

<p>True, a sufficiently stupid programmer <em>could</em> create a new stream when he intended to write to <code>std::cout</code>, and true, a singleton implementation would have prevented that. But is it worth it? When was the last time you saw someone <em>accidentally</em> invoke <code>std::ostream() &lt;&lt; "Hello world";</code>, when they intended to write <code>std::cout &lt;&lt; "Hello world";</code>? It’s not the most common typo I’ve seen.</p>

<p>We don’t <em>need</em> to prevent multiple instantiations. If we want only one instance, we just instantiate the class once, and refer to that instance whenever we need it, end of story. We don’t need the compiler to slap us over the wrists if we do create multiple instances, because we never do so by mistake. If we do it, it’s because we have a reason. It’s because our initial assumption that only one instance was needed, turned out to be wrong!</p>

<p>So there you have it. A singleton combines two <em>negative</em> qualities. It takes the “you can never create a second instance of this class” constraint, which hardly ever makes sense, and even when it does, does not typically need to be enforced by the compiler, <em>and combines it with a global object</em>, giving us all the downsides of both!</p>

<p>Two wrongs don’t make a right. Not even if they were described as a good idea by some guys 15 years ago. They’re still no greater than the sum of their parts: two wrongs. One bad thing combined with another bad thing, creating a <em>very</em> bad thing.</p>

<p>Too many programmers rely heavily on singletons to solve a problem they never had. They never <em>needed</em> a compile-time guarantee that multiple instances of a class can never be created. They just needed one instance to be created.</p>

<p>Sometimes, we do need globals, yes. In those cases, make old-fashioned globals. Use static class members, or if the language allows it, global (non-member) objects. Or use the Monostate pattern, or whatever you feel is the cleanest solution. But remember that the problem you’re trying to solve is “enabling global access to this data”. No more, no less. You do <em>not</em> want a solution which sneaks completely unrelated constraints and limitations in through the back door.</p>

<p>And while I can’t personally think of many cases where this is true, you <em>might</em> also run into situations where it is truly <em>necessary</em> to prevent more than one instance of a class from ever existing. Again, I can’t think of what situation this might be, but I won’t rule out that it can occur. If it does, then enforce <em>that</em> constraint alone. But don’t go around providing <em>global access</em> to the object as well. Whatever specialized purpose your “one instance only” class serves, it’s highly unlikely that <em>everyone</em> should be allowed access to it. So don’t make it a global.</p>

<p>Most of the time, your classes should have neither of these attributes. Sometimes, rarely, they may need <em>one</em> of them. But the singleton pattern imbues the class with <em>both</em> properties, and <em>that</em> is just a plain bad idea.</p>
]]></content:encoded>
			<wfw:commentRss>http://jalf.dk/blog/2010/03/singletons-solving-problems-you-didnt-know-you-never-had-since-1995/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
	</channel>
</rss>

