<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	>
<channel>
	<title>Comments on: What&#8217;s so bad about the Singleton?</title>
	<atom:link href="http://www.sitepoint.com/blogs/2008/02/13/whats-so-bad-about-the-singleton/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.sitepoint.com/blogs/2008/02/13/whats-so-bad-about-the-singleton/</link>
	<description>News, opinion, and fresh thinking for web developers and designers. The official podcast of sitepoint.com.</description>
	<pubDate>Tue, 02 Dec 2008 04:19:34 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.5</generator>
		<item>
		<title>By: Benjiro</title>
		<link>http://www.sitepoint.com/blogs/2008/02/13/whats-so-bad-about-the-singleton/#comment-820329</link>
		<dc:creator>Benjiro</dc:creator>
		<pubDate>Mon, 03 Nov 2008 03:30:43 +0000</pubDate>
		<guid isPermaLink="false">http://www.sitepoint.com/blogs/2008/02/13/whats-so-bad-about-the-singleton/#comment-820329</guid>
		<description>&lt;blockquote&gt;Some commenters seem averse to passing references to classes as function arguments. This could be for a few reasons: a) they don’t understand call by reference, b) their functions already have a prohibitive number of arguments, c) they’re code base is highly dependent on their usage of singletons.&lt;/blockquote&gt;

One can argue that some people have never seen a project with 400.000 lines or larger. Trust me on this one, passing references as function arguments is inefficient. You are constantly moving the DB connection as a reference from one function to another, to another, to another. Is that bad? No. Is it nice coding? No. Code what you need, where you need it. 

If you need the ref in function Z, but function Z is located at X -&#62; Y -&#62; Z, your wasting time, and code overview with these constant reference passing. Sure, a registry ref solves that problem if you need to deal with several dbi, param etc, but essentially, your doing the same thing over &#38; over again. Again, code things where you need it. Its a wast of code space, to constantly pass references when you don't need them, but you "might" need them later on. O wait, function Y did not need the ref, now we need to update function Y, and everywhere function Y is called to include it. Or, your like i said before, forced to constantly keep pasting the reference with all your function, even when they are not needed.

This discussion to me looks like almost all the MVC discussions i have read. No, thats not real MVC, this is. No, thats wrong, this is. No, your all wrong, that is. *grumbles*

One of the recurring arguments is: But we need to manage multi different database connections bla bla bla ... No you don't. Is it so hard to create a singleton for mysql, and one of oracle? Or equip your singleton to deal with multi connection types. There are lots of examples out there on the net ( some bad, some excellent ).

It looks like people are going overboard in a rabbit war, over no good reason. Sure, global declarations are something to be avoided if possible, but lets face it. If you need your Database connection at Z, you are not going to wast time, reconnection the connection every! time. So, you initial the DB connection as a singleton, or use a reference, or use a global ( a ref registry is the same as a ref dbi, no mather how you dress it up ). Thats it. The singleton in my eyes, saves code that you don't need to write again, again. A proper implementation of a singleton prevents it from getting altered in a improper way.

Don't underestimate the mess that can be created with a passing a ref all over the place. Seen it before. The arguments that can be used to put down a singleton, can in a lot of cases also be used against the other methods.

KISS people, KISS. The proper tool for the job. Unless there is a specific performance, bugs, or other problematic things around them, there is no reason to avoid singleton usage. A &lt;strong&gt;good&lt;/strong&gt; implemented singleton is a good solution. All the rest is just people wanting to push there definition of "good" programming on each other. Just like almost any MVC thread where everybody has there own definition of "good" MVC.</description>
		<content:encoded><![CDATA[<blockquote><p>Some commenters seem averse to passing references to classes as function arguments. This could be for a few reasons: a) they don’t understand call by reference, b) their functions already have a prohibitive number of arguments, c) they’re code base is highly dependent on their usage of singletons.</p></blockquote>
<p>One can argue that some people have never seen a project with 400.000 lines or larger. Trust me on this one, passing references as function arguments is inefficient. You are constantly moving the DB connection as a reference from one function to another, to another, to another. Is that bad? No. Is it nice coding? No. Code what you need, where you need it. </p>
<p>If you need the ref in function Z, but function Z is located at X -&gt; Y -&gt; Z, your wasting time, and code overview with these constant reference passing. Sure, a registry ref solves that problem if you need to deal with several dbi, param etc, but essentially, your doing the same thing over &amp; over again. Again, code things where you need it. Its a wast of code space, to constantly pass references when you don&#8217;t need them, but you &#8220;might&#8221; need them later on. O wait, function Y did not need the ref, now we need to update function Y, and everywhere function Y is called to include it. Or, your like i said before, forced to constantly keep pasting the reference with all your function, even when they are not needed.</p>
<p>This discussion to me looks like almost all the MVC discussions i have read. No, thats not real MVC, this is. No, thats wrong, this is. No, your all wrong, that is. *grumbles*</p>
<p>One of the recurring arguments is: But we need to manage multi different database connections bla bla bla &#8230; No you don&#8217;t. Is it so hard to create a singleton for mysql, and one of oracle? Or equip your singleton to deal with multi connection types. There are lots of examples out there on the net ( some bad, some excellent ).</p>
<p>It looks like people are going overboard in a rabbit war, over no good reason. Sure, global declarations are something to be avoided if possible, but lets face it. If you need your Database connection at Z, you are not going to wast time, reconnection the connection every! time. So, you initial the DB connection as a singleton, or use a reference, or use a global ( a ref registry is the same as a ref dbi, no mather how you dress it up ). Thats it. The singleton in my eyes, saves code that you don&#8217;t need to write again, again. A proper implementation of a singleton prevents it from getting altered in a improper way.</p>
<p>Don&#8217;t underestimate the mess that can be created with a passing a ref all over the place. Seen it before. The arguments that can be used to put down a singleton, can in a lot of cases also be used against the other methods.</p>
<p>KISS people, KISS. The proper tool for the job. Unless there is a specific performance, bugs, or other problematic things around them, there is no reason to avoid singleton usage. A <strong>good</strong> implemented singleton is a good solution. All the rest is just people wanting to push there definition of &#8220;good&#8221; programming on each other. Just like almost any MVC thread where everybody has there own definition of &#8220;good&#8221; MVC.</p>]]></content:encoded>
	</item>
	<item>
		<title>By: bestweb</title>
		<link>http://www.sitepoint.com/blogs/2008/02/13/whats-so-bad-about-the-singleton/#comment-725759</link>
		<dc:creator>bestweb</dc:creator>
		<pubDate>Mon, 19 May 2008 04:22:16 +0000</pubDate>
		<guid isPermaLink="false">http://www.sitepoint.com/blogs/2008/02/13/whats-so-bad-about-the-singleton/#comment-725759</guid>
		<description>Alright, this might have already been hashed out but I cannot bother myself with reading all the comments. There are several problems with singletons ranging from predictability to garbage collection.

&lt;strong&gt;Predictability/Hard Coupling:&lt;/strong&gt;
These two issues are closely related. It is difficult to measure just how dependent (in this case, highly) on piece of code is to another when inputs aren't explicitly being passed around. A function is deterministic insofar as given the same set of inputs it will return a single output. Unknowingly outputting or modifying the state of a foreign object is a side-effect. Given a singleton, it is impossible to say a function/method is deterministic. This is the case for two reasons: i) given that the singleton is not explicitly passed to the function, for any number of function calls there is no measure to show that the singleton's state hasn't changed, and given code dependent on the state of the singleton, the function's return will be different, ie: not deterministic; ii) the function might modify the state of the singleton, the altering the rest of the program in an unpredictable way.

&lt;strong&gt;Garbage Collection&lt;/strong&gt;
Although PHP runs as distinct processes, this is still applicable and definitely generalizable to other languages. When does a singleton object get garbage collected? In the case of PHP, it is likely collected when the current process is terminated because it never loses scope--regardless of if it used in the program or not. In essence, this is a memory leak.

&lt;strong&gt;Inheritance&lt;/strong&gt;
If the singleton is implemented by using a class (eg: a registry), then extending the singleton class is a pain. Given a purposeful singleton class, extending it and using both the parent and child subclasses causes unwanted overlap with the static members. Obviously, this is an avoidable problem that leads to another unfortunate problem: boilerplate code because each singleton class needs to be separate.

This should be an indication to anyone using singletons that they are doing something wrong. In general, using singletons with classes is a hack to make object-oriented code more procedural. Boilerplate code is a signal to refactor code.

&lt;strong&gt;Final Thoughts&lt;/strong&gt;
The general pattern I see is that for new programmers, the singleton appears to be a panacea. Unfortunately, the benefits of singletons are more apparent than real. At first, their conveniences seem amazing. However, as code bases grow, singletons have the effect of making code less maintainable. Their intended use--to have one and only one instance of a particular class--can be factored out into other solutions. Some commenters seem averse to passing references to classes as function arguments. This could be for a few reasons: a) they don't understand call by reference, b) their functions already have a prohibitive number of arguments, c) they're code base is highly dependent on their usage of singletons. Besides the last one, these problems are trivial. So why ought one pass objects by reference as inputs to places where they are used? One of the strongest points is that the code becomes implementation independent. The second you use a singleton, you are locked into the same instance of the same class. As kyberfabrikken exampled with database connections, by passing dependencies as arguments to functions, you are not limited to only one resource, and the same is generalized to one implementation. If this doesn't seem important then please take a minute to think about it as the implication is important with respect to modularity and maintainability.</description>
		<content:encoded><![CDATA[<p>Alright, this might have already been hashed out but I cannot bother myself with reading all the comments. There are several problems with singletons ranging from predictability to garbage collection.</p>
<p><strong>Predictability/Hard Coupling:</strong><br />
These two issues are closely related. It is difficult to measure just how dependent (in this case, highly) on piece of code is to another when inputs aren&#8217;t explicitly being passed around. A function is deterministic insofar as given the same set of inputs it will return a single output. Unknowingly outputting or modifying the state of a foreign object is a side-effect. Given a singleton, it is impossible to say a function/method is deterministic. This is the case for two reasons: i) given that the singleton is not explicitly passed to the function, for any number of function calls there is no measure to show that the singleton&#8217;s state hasn&#8217;t changed, and given code dependent on the state of the singleton, the function&#8217;s return will be different, ie: not deterministic; ii) the function might modify the state of the singleton, the altering the rest of the program in an unpredictable way.</p>
<p><strong>Garbage Collection</strong><br />
Although PHP runs as distinct processes, this is still applicable and definitely generalizable to other languages. When does a singleton object get garbage collected? In the case of PHP, it is likely collected when the current process is terminated because it never loses scope&#8211;regardless of if it used in the program or not. In essence, this is a memory leak.</p>
<p><strong>Inheritance</strong><br />
If the singleton is implemented by using a class (eg: a registry), then extending the singleton class is a pain. Given a purposeful singleton class, extending it and using both the parent and child subclasses causes unwanted overlap with the static members. Obviously, this is an avoidable problem that leads to another unfortunate problem: boilerplate code because each singleton class needs to be separate.</p>
<p>This should be an indication to anyone using singletons that they are doing something wrong. In general, using singletons with classes is a hack to make object-oriented code more procedural. Boilerplate code is a signal to refactor code.</p>
<p><strong>Final Thoughts</strong><br />
The general pattern I see is that for new programmers, the singleton appears to be a panacea. Unfortunately, the benefits of singletons are more apparent than real. At first, their conveniences seem amazing. However, as code bases grow, singletons have the effect of making code less maintainable. Their intended use&#8211;to have one and only one instance of a particular class&#8211;can be factored out into other solutions. Some commenters seem averse to passing references to classes as function arguments. This could be for a few reasons: a) they don&#8217;t understand call by reference, b) their functions already have a prohibitive number of arguments, c) they&#8217;re code base is highly dependent on their usage of singletons. Besides the last one, these problems are trivial. So why ought one pass objects by reference as inputs to places where they are used? One of the strongest points is that the code becomes implementation independent. The second you use a singleton, you are locked into the same instance of the same class. As kyberfabrikken exampled with database connections, by passing dependencies as arguments to functions, you are not limited to only one resource, and the same is generalized to one implementation. If this doesn&#8217;t seem important then please take a minute to think about it as the implication is important with respect to modularity and maintainability.</p>]]></content:encoded>
	</item>
	<item>
		<title>By: Sly Gryphon</title>
		<link>http://www.sitepoint.com/blogs/2008/02/13/whats-so-bad-about-the-singleton/#comment-693115</link>
		<dc:creator>Sly Gryphon</dc:creator>
		<pubDate>Wed, 16 Apr 2008 01:20:08 +0000</pubDate>
		<guid isPermaLink="false">http://www.sitepoint.com/blogs/2008/02/13/whats-so-bad-about-the-singleton/#comment-693115</guid>
		<description>I don't see what the comments on static binding have to do specifically with singletons, as opposed to other ways of giving class A a reference to an instance of class S.

"If class A has a dependency on class S injected, then there is a strong coupling between A and S."

"If class A has class S passed into a method, then there is a strong coupling between A and S."

In all cases, if class A calls method S.Foo(), then there is a compile time dependency from A to S. Note that in all three cases the actual instance of S used can vary (including a subclass). 

The primary difference between passing as an argument, dependency injection and singleton is how easy it is to change *when* the instance of S used is changed. 

- For a method argument it is easy to use a different S each time. (You can use the same S each time if you want).

- For dependency injection it is easiest to set the instance of S once when A is created; if you want to use the same S this is easier than passing an extra parameter each time. (Note that you *could* change the instance of S held by A before each call, but it's not as easy as if passed via a method.)

- For singleton it is easiest to set the instance of S once for the whole program. (Note you can still change that instance before each call).

Another consideration when 'changing' the instance of S is threading. If there are multiple threads potentially accessing the singleton (or class A's injected S), then you would need to lock to isolate the different S's. (Passing in as a method argument does not need the lock).

Note the same things can be done with all designs, just the ease of doing them differs. If you need a different instance of S each time, have multithreading issues, and have S readily available, it does not make sense to use a singleton and have to lock it each time (in fact, it's stupid).

On the other hand, if you only have one S, the same S used by all, and it has no state that is going to screw up threads, then a singleton is easier than an additional argument passed through all layers of your methods.

One other aspect of the static binding that does differ between the methods is how obvious the static binding is: a method clearing has a paramter S; dependency injection has parameter S on the constructor (or a property of type S); use of a a singleton, however, is not visible in the public interface. (Many other solutions, such as extracting from a generic registry, also don't explicitly have S in the public interface).

Remember, in all these cases, that the Singleton pattern does not prevent you having multiple instances (e.g. one per thread) or varying instances (the singleton can be any subclass of S). These are actually two of the benefits of the pattern from the original Design Patterns book (consequences 3. Permits refinement and 4. Permits variable number of instances).

In fact, the ability to use a subclass is one of the primary reasons in Design Patterns for using the Singleton pattern: "Use the Singleton pattern when ... instance should be extensible by subclassing and should be able to use an extended instance without modifying their code."

From the point of view of unit testing, this is brilliant: the target code uses the singleton to provide services/functions, and all your test code needs to do is configure the singleton instance with a stub implementation (e.g. mock).

A final note: using a registry to hold a collection of instances is one of the implementation issues actually discussed in Design Patterns as a "flexible approach". In Patterns of Enterprise Application Architecture, Fowler further expands on the Registry pattern, as a particular implementation of Singleton.

Sly Gryphon</description>
		<content:encoded><![CDATA[<p>I don&#8217;t see what the comments on static binding have to do specifically with singletons, as opposed to other ways of giving class A a reference to an instance of class S.</p>
<p>&#8220;If class A has a dependency on class S injected, then there is a strong coupling between A and S.&#8221;</p>
<p>&#8220;If class A has class S passed into a method, then there is a strong coupling between A and S.&#8221;</p>
<p>In all cases, if class A calls method S.Foo(), then there is a compile time dependency from A to S. Note that in all three cases the actual instance of S used can vary (including a subclass). </p>
<p>The primary difference between passing as an argument, dependency injection and singleton is how easy it is to change *when* the instance of S used is changed. </p>
<p>- For a method argument it is easy to use a different S each time. (You can use the same S each time if you want).</p>
<p>- For dependency injection it is easiest to set the instance of S once when A is created; if you want to use the same S this is easier than passing an extra parameter each time. (Note that you *could* change the instance of S held by A before each call, but it&#8217;s not as easy as if passed via a method.)</p>
<p>- For singleton it is easiest to set the instance of S once for the whole program. (Note you can still change that instance before each call).</p>
<p>Another consideration when &#8216;changing&#8217; the instance of S is threading. If there are multiple threads potentially accessing the singleton (or class A&#8217;s injected S), then you would need to lock to isolate the different S&#8217;s. (Passing in as a method argument does not need the lock).</p>
<p>Note the same things can be done with all designs, just the ease of doing them differs. If you need a different instance of S each time, have multithreading issues, and have S readily available, it does not make sense to use a singleton and have to lock it each time (in fact, it&#8217;s stupid).</p>
<p>On the other hand, if you only have one S, the same S used by all, and it has no state that is going to screw up threads, then a singleton is easier than an additional argument passed through all layers of your methods.</p>
<p>One other aspect of the static binding that does differ between the methods is how obvious the static binding is: a method clearing has a paramter S; dependency injection has parameter S on the constructor (or a property of type S); use of a a singleton, however, is not visible in the public interface. (Many other solutions, such as extracting from a generic registry, also don&#8217;t explicitly have S in the public interface).</p>
<p>Remember, in all these cases, that the Singleton pattern does not prevent you having multiple instances (e.g. one per thread) or varying instances (the singleton can be any subclass of S). These are actually two of the benefits of the pattern from the original Design Patterns book (consequences 3. Permits refinement and 4. Permits variable number of instances).</p>
<p>In fact, the ability to use a subclass is one of the primary reasons in Design Patterns for using the Singleton pattern: &#8220;Use the Singleton pattern when &#8230; instance should be extensible by subclassing and should be able to use an extended instance without modifying their code.&#8221;</p>
<p>From the point of view of unit testing, this is brilliant: the target code uses the singleton to provide services/functions, and all your test code needs to do is configure the singleton instance with a stub implementation (e.g. mock).</p>
<p>A final note: using a registry to hold a collection of instances is one of the implementation issues actually discussed in Design Patterns as a &#8220;flexible approach&#8221;. In Patterns of Enterprise Application Architecture, Fowler further expands on the Registry pattern, as a particular implementation of Singleton.</p>
<p>Sly Gryphon</p>]]></content:encoded>
	</item>
	<item>
		<title>By: fresh</title>
		<link>http://www.sitepoint.com/blogs/2008/02/13/whats-so-bad-about-the-singleton/#comment-660333</link>
		<dc:creator>fresh</dc:creator>
		<pubDate>Tue, 25 Mar 2008 12:14:53 +0000</pubDate>
		<guid isPermaLink="false">http://www.sitepoint.com/blogs/2008/02/13/whats-so-bad-about-the-singleton/#comment-660333</guid>
		<description>Hm, what about inheritance?
One more place where we use explicit classnames!

In our project we are already at a point where I would like to have "dynamic inheritance".

Our pages are implemented as classes deriving from a MyProjectDefaultPage class for the unified layout. Quite a nice thing, because this allows a huge number of extension points. For instance, for the top menu, we can simply reimplement the "getTopmenuActiveItem" and return the name of the active menu item. And "getSubmenuItems" to return a formal list of items to show up in the submenu. Then we can make one more layer of subclasses that all share this submenu, but have different implementations of "getSubmenuActiveItem".

(I hope this was understandable)

Now we might get at a point where we want to introduce skins. For this we would want to replace or extend the MyProjectDefaultPage with something else.

Ideally something like this:

$active_skin = 'AlternativeSkin';

AlternativeSkin::SomeSpecificPage extends DefaultSkin::SomeSpecificPage

SomeSpecificPage extends $active_skin::DefaultPage

$active_skin::DefaultPage extends DefaultSkin::DefaultPage

---

This time it's not about singletons, but still about static symbols that we want to be dynamic.</description>
		<content:encoded><![CDATA[<p>Hm, what about inheritance?<br />
One more place where we use explicit classnames!</p>
<p>In our project we are already at a point where I would like to have &#8220;dynamic inheritance&#8221;.</p>
<p>Our pages are implemented as classes deriving from a MyProjectDefaultPage class for the unified layout. Quite a nice thing, because this allows a huge number of extension points. For instance, for the top menu, we can simply reimplement the &#8220;getTopmenuActiveItem&#8221; and return the name of the active menu item. And &#8220;getSubmenuItems&#8221; to return a formal list of items to show up in the submenu. Then we can make one more layer of subclasses that all share this submenu, but have different implementations of &#8220;getSubmenuActiveItem&#8221;.</p>
<p>(I hope this was understandable)</p>
<p>Now we might get at a point where we want to introduce skins. For this we would want to replace or extend the MyProjectDefaultPage with something else.</p>
<p>Ideally something like this:</p>
<p>$active_skin = &#8216;AlternativeSkin&#8217;;</p>
<p>AlternativeSkin::SomeSpecificPage extends DefaultSkin::SomeSpecificPage</p>
<p>SomeSpecificPage extends $active_skin::DefaultPage</p>
<p>$active_skin::DefaultPage extends DefaultSkin::DefaultPage</p>
<p>&#8212;</p>
<p>This time it&#8217;s not about singletons, but still about static symbols that we want to be dynamic.</p>]]></content:encoded>
	</item>
	<item>
		<title>By: SitePoint Blogs &#187; Interpreting the Results of the SitePoint Reader Survey, Part 2: Content</title>
		<link>http://www.sitepoint.com/blogs/2008/02/13/whats-so-bad-about-the-singleton/#comment-656125</link>
		<dc:creator>SitePoint Blogs &#187; Interpreting the Results of the SitePoint Reader Survey, Part 2: Content</dc:creator>
		<pubDate>Mon, 17 Mar 2008 01:52:42 +0000</pubDate>
		<guid isPermaLink="false">http://www.sitepoint.com/blogs/2008/02/13/whats-so-bad-about-the-singleton/#comment-656125</guid>
		<description>[...] categories were a bit vague. For example &#8220;content suggestion&#8221; covered everything from more blog posts about singletons in PHP to more interviews with leading [...]</description>
		<content:encoded><![CDATA[<p>[&#8230;] categories were a bit vague. For example &#8220;content suggestion&#8221; covered everything from more blog posts about singletons in PHP to more interviews with leading [&#8230;]</p>]]></content:encoded>
	</item>
	<item>
		<title>By: McGruff</title>
		<link>http://www.sitepoint.com/blogs/2008/02/13/whats-so-bad-about-the-singleton/#comment-653027</link>
		<dc:creator>McGruff</dc:creator>
		<pubDate>Wed, 12 Mar 2008 00:51:58 +0000</pubDate>
		<guid isPermaLink="false">http://www.sitepoint.com/blogs/2008/02/13/whats-so-bad-about-the-singleton/#comment-653027</guid>
		<description>Singletons are unequivocally a bad choice for the reasons mentioned above (although a singleton registry can have its uses). You won't ever see them in a good OOP design. 

The problem with encapsulating code in classes is that everything is locked up in separate components: how to get all the bits talking to each other? Who gets a reference to what is the basic problem of OOP design. Simply making things global to get around that is a bit of a cop out. Instead you should figure out how to pass objects around where they are needed.

Factories, a registry, or a dependency injection container can manage lifecycle if you genuinely want a single instance. Object assembly is really a layer all of its own. Good things happen when you pull that out from the rest of the code ;)</description>
		<content:encoded><![CDATA[<p>Singletons are unequivocally a bad choice for the reasons mentioned above (although a singleton registry can have its uses). You won&#8217;t ever see them in a good OOP design. </p>
<p>The problem with encapsulating code in classes is that everything is locked up in separate components: how to get all the bits talking to each other? Who gets a reference to what is the basic problem of OOP design. Simply making things global to get around that is a bit of a cop out. Instead you should figure out how to pass objects around where they are needed.</p>
<p>Factories, a registry, or a dependency injection container can manage lifecycle if you genuinely want a single instance. Object assembly is really a layer all of its own. Good things happen when you pull that out from the rest of the code ;)</p>]]></content:encoded>
	</item>
	<item>
		<title>By: fresh</title>
		<link>http://www.sitepoint.com/blogs/2008/02/13/whats-so-bad-about-the-singleton/#comment-643507</link>
		<dc:creator>fresh</dc:creator>
		<pubDate>Tue, 26 Feb 2008 13:57:35 +0000</pubDate>
		<guid isPermaLink="false">http://www.sitepoint.com/blogs/2008/02/13/whats-so-bad-about-the-singleton/#comment-643507</guid>
		<description>@myself:
&lt;blockquote&gt;The benefit I see in static class methods (eventually with private static variables that behave like singletons) in bootstrapping is encapsulation. We can have private methods that load a bunch of ini files, etc. Better than having all that in spaghetti. And, we don’t have to say “load setting X” and later “use setting X” - we can just say MySetup::getX(), and the setup class will load the things if-not-done-yet.&lt;/blockquote&gt;

Even better: Assume that we usually write some defaults into the $_SESSION when it's empty, and eventually allow the user to switch these values. With a singleton or static methods, we can encapsulate all that: "MySettingX::get()" will look if the session value is already set, and if not fill it with defaults.</description>
		<content:encoded><![CDATA[<p>@myself:</p>
<blockquote><p>The benefit I see in static class methods (eventually with private static variables that behave like singletons) in bootstrapping is encapsulation. We can have private methods that load a bunch of ini files, etc. Better than having all that in spaghetti. And, we don’t have to say “load setting X” and later “use setting X” - we can just say MySetup::getX(), and the setup class will load the things if-not-done-yet.</p></blockquote>
<p>Even better: Assume that we usually write some defaults into the $_SESSION when it&#8217;s empty, and eventually allow the user to switch these values. With a singleton or static methods, we can encapsulate all that: &#8220;MySettingX::get()&#8221; will look if the session value is already set, and if not fill it with defaults.</p>]]></content:encoded>
	</item>
	<item>
		<title>By: fresh</title>
		<link>http://www.sitepoint.com/blogs/2008/02/13/whats-so-bad-about-the-singleton/#comment-643495</link>
		<dc:creator>fresh</dc:creator>
		<pubDate>Tue, 26 Feb 2008 13:32:41 +0000</pubDate>
		<guid isPermaLink="false">http://www.sitepoint.com/blogs/2008/02/13/whats-so-bad-about-the-singleton/#comment-643495</guid>
		<description>Some comments.

&lt;em&gt;(I apologize for that much long-winded detail and eventually going off-topic, but without that it will be hard to see how the concepts apply to reality.)&lt;/em&gt;

&lt;blockquote&gt;The other benefit is that a single monolithic registry is the first step towards a finer grained collection of registries. You can fairly easy refactor towards having a number of registries. Eventually these registries might be possible to turn into actual objects.&lt;/blockquote&gt;

Are we talking about different registries that have to be passed one-by-one? Like

&lt;code&gt;$controller = new MyComponentController($registry1, $registry2, $registry3);&lt;/code&gt;

or

&lt;code&gt;$controller = new MyComponentController();
$controller-&#62;setReg1($registry1);
$controller-&#62;setReg2($registry2);
$controller-&#62;setReg3($registry3);&lt;/code&gt;

or

&lt;code&gt;$registry-&#62;set('section1', $registry1);
$registry-&#62;set('section2', $registry2);
$registry-&#62;set('section3', $registry3);
$controller = new MyComponentController($registry);&lt;/code&gt;

As I understand, these are all different ways of dependency injection. What they have in common is that we either have to know which information the component will need, or that we have to generously inject everything.


Now, let's have a look at an &lt;strong&gt;example&lt;/strong&gt;.
Some things that our view classes (or even the templates) will need:
- information about the user and the session: Does he have admin rights? In which language is he surfing? Depending on these things, some layout elements might not be displayed, or displayed in a different way.
- shared layout elements (let's call them widgets) like menu, calendar, advanced time display ('this was posted * minutes ago'), avatar pictures etc.
- Some of these shared layout elements might again need information about the user, the environment etc, or might even need an own database connection (the calendar for instance, to look into the calendar database).
- In the current design there is a 'page' object where different layout components are buffered, to be finally assembled in a centralized place (page.php). I don't like the specific way we do it, but I'm also not going to change it that soon.

Typically, our controller will not know which of these things are needed in the view classes (except for the page object, which is needed in any case) - a designer might choose, out of the blue, to use a calendar or other layout elements, or to add some power controls that require admin rights.

With dependency injection or registry we would have to pass around a 'widget factory', a 'user' object etc, all injected one-by-one with setters or constructor parameters, or stuffed into a passed-around registry. And the widget factory for itself would also need to know how to get information about the user and the database, and pass that information to those widgets which need it. (another question is, how MVC can be applied to autonomous layout widgets)

Currently we do much of the above with singletons and static functions. Maybe at the cost of flexibility, but so far we have not really missed it - most of all because we did not try anything that requires flexibility. What we win is transparency - which means, you always know where a function is implemented.


&lt;blockquote&gt;However, there is a big difference between not redefining defaults and actively introducing them. What I’m advocating, is that userland code should refrain from introducing new static symbols.&lt;/blockquote&gt;

Ok with that. Maybe the '+' example was a bit exaggerated anyway.

Some static symbols in PHP are the $_SESSION, $_GET and other global variables. Maybe the ideal way would be to hide these things in objects. But, it does already help to hide these things behind static class methods - if only for making it easier to prevent arbitrary write access.

Another typical example for static symbols is a class constructor, or a static factory method. If we don't want static symbols to be used globally, we have to take care that a explicit constructors (as any static symbols, including singletons and static factory methods) are only used in the "bootstrapper" (where the hell does this word come from) and inside the component they belong to.


&lt;blockquote&gt;I would say that you could equally well write the bootstrapping without singletons, as you can with.&lt;/blockquote&gt;

The benefit I see in static class methods (eventually with private static variables that behave like singletons) in bootstrapping is encapsulation. We can have private methods that load a bunch of ini files, etc. Better than having all that in spaghetti. And, we don't have to say "load setting X" and later "use setting X" - we can just say MySetup::getX(), and the setup class will load the things if-not-done-yet.</description>
		<content:encoded><![CDATA[<p>Some comments.</p>
<p><em>(I apologize for that much long-winded detail and eventually going off-topic, but without that it will be hard to see how the concepts apply to reality.)</em></p>
<blockquote><p>The other benefit is that a single monolithic registry is the first step towards a finer grained collection of registries. You can fairly easy refactor towards having a number of registries. Eventually these registries might be possible to turn into actual objects.</p></blockquote>
<p>Are we talking about different registries that have to be passed one-by-one? Like</p>
<code>$controller = new MyComponentController($registry1, $registry2, $registry3);</code>
<p>or</p>
<code>$controller = new MyComponentController();
$controller-&gt;setReg1($registry1);
$controller-&gt;setReg2($registry2);
$controller-&gt;setReg3($registry3);</code>
<p>or</p>
<code>$registry-&gt;set('section1', $registry1);
$registry-&gt;set('section2', $registry2);
$registry-&gt;set('section3', $registry3);
$controller = new MyComponentController($registry);</code>
<p>As I understand, these are all different ways of dependency injection. What they have in common is that we either have to know which information the component will need, or that we have to generously inject everything.</p>
<p>Now, let&#8217;s have a look at an <strong>example</strong>.<br />
Some things that our view classes (or even the templates) will need:<br />
- information about the user and the session: Does he have admin rights? In which language is he surfing? Depending on these things, some layout elements might not be displayed, or displayed in a different way.<br />
- shared layout elements (let&#8217;s call them widgets) like menu, calendar, advanced time display (&#8217;this was posted * minutes ago&#8217;), avatar pictures etc.<br />
- Some of these shared layout elements might again need information about the user, the environment etc, or might even need an own database connection (the calendar for instance, to look into the calendar database).<br />
- In the current design there is a &#8216;page&#8217; object where different layout components are buffered, to be finally assembled in a centralized place (page.php). I don&#8217;t like the specific way we do it, but I&#8217;m also not going to change it that soon.</p>
<p>Typically, our controller will not know which of these things are needed in the view classes (except for the page object, which is needed in any case) - a designer might choose, out of the blue, to use a calendar or other layout elements, or to add some power controls that require admin rights.</p>
<p>With dependency injection or registry we would have to pass around a &#8216;widget factory&#8217;, a &#8216;user&#8217; object etc, all injected one-by-one with setters or constructor parameters, or stuffed into a passed-around registry. And the widget factory for itself would also need to know how to get information about the user and the database, and pass that information to those widgets which need it. (another question is, how MVC can be applied to autonomous layout widgets)</p>
<p>Currently we do much of the above with singletons and static functions. Maybe at the cost of flexibility, but so far we have not really missed it - most of all because we did not try anything that requires flexibility. What we win is transparency - which means, you always know where a function is implemented.</p>
<blockquote><p>However, there is a big difference between not redefining defaults and actively introducing them. What I’m advocating, is that userland code should refrain from introducing new static symbols.</p></blockquote>
<p>Ok with that. Maybe the &#8216;+&#8217; example was a bit exaggerated anyway.</p>
<p>Some static symbols in PHP are the $_SESSION, $_GET and other global variables. Maybe the ideal way would be to hide these things in objects. But, it does already help to hide these things behind static class methods - if only for making it easier to prevent arbitrary write access.</p>
<p>Another typical example for static symbols is a class constructor, or a static factory method. If we don&#8217;t want static symbols to be used globally, we have to take care that a explicit constructors (as any static symbols, including singletons and static factory methods) are only used in the &#8220;bootstrapper&#8221; (where the hell does this word come from) and inside the component they belong to.</p>
<blockquote><p>I would say that you could equally well write the bootstrapping without singletons, as you can with.</p></blockquote>
<p>The benefit I see in static class methods (eventually with private static variables that behave like singletons) in bootstrapping is encapsulation. We can have private methods that load a bunch of ini files, etc. Better than having all that in spaghetti. And, we don&#8217;t have to say &#8220;load setting X&#8221; and later &#8220;use setting X&#8221; - we can just say MySetup::getX(), and the setup class will load the things if-not-done-yet.</p>]]></content:encoded>
	</item>
	<item>
		<title>By: kyberfabrikken</title>
		<link>http://www.sitepoint.com/blogs/2008/02/13/whats-so-bad-about-the-singleton/#comment-643129</link>
		<dc:creator>kyberfabrikken</dc:creator>
		<pubDate>Mon, 25 Feb 2008 23:11:18 +0000</pubDate>
		<guid isPermaLink="false">http://www.sitepoint.com/blogs/2008/02/13/whats-so-bad-about-the-singleton/#comment-643129</guid>
		<description>&lt;blockquote&gt;
To me, this post is the equivalent of saying "Hammers suck because I used one once to open a box of glasses and all the glasses broke."
&lt;/blockquote&gt;
And to me, this quote is the equivalent of saying "Guns don't kill people. People with guns kill people."

In a narrow sense, you are right but the way most people use singletons, isn't as it's described in GoF. In this case, it's a matter of signalling intend. If you implement a class as a singleton, an outside programmer will naturally suspect that it's used for gaining global access deep from within your program. The uncertainty can be damaging on its own.</description>
		<content:encoded><![CDATA[<blockquote><p>
To me, this post is the equivalent of saying &#8220;Hammers suck because I used one once to open a box of glasses and all the glasses broke.&#8221;
</p></blockquote>
<p>And to me, this quote is the equivalent of saying &#8220;Guns don&#8217;t kill people. People with guns kill people.&#8221;</p>
<p>In a narrow sense, you are right but the way most people use singletons, isn&#8217;t as it&#8217;s described in GoF. In this case, it&#8217;s a matter of signalling intend. If you implement a class as a singleton, an outside programmer will naturally suspect that it&#8217;s used for gaining global access deep from within your program. The uncertainty can be damaging on its own.</p>]]></content:encoded>
	</item>
	<item>
		<title>By: kyberfabrikken</title>
		<link>http://www.sitepoint.com/blogs/2008/02/13/whats-so-bad-about-the-singleton/#comment-643128</link>
		<dc:creator>kyberfabrikken</dc:creator>
		<pubDate>Mon, 25 Feb 2008 23:08:44 +0000</pubDate>
		<guid isPermaLink="false">http://www.sitepoint.com/blogs/2008/02/13/whats-so-bad-about-the-singleton/#comment-643128</guid>
		<description>@fresh
Those are all very good points. I'll try to address them in sequence.

&lt;blockquote&gt;
Ok, but if we pass around everything in a registry instead, then how can we know what a component does with the passed-around object? I see the same problems as before: The registry grows so big and is used in so many places, that again everything depends from everything.
&lt;/blockquote&gt;
That is true. There are two things that makes the registry an improvement over a singleton. The first is that it offers a flex-point; This is especially useful in testing, since it allows you to substitute a single component with a mock. The other benefit is that a single monolithic registry is the first step towards a finer grained collection of registries. You can fairly easy refactor towards having a number of registries. Eventually these registries might be possible to turn into actual objects.

But eventually, a registry has one of the same root-problems as singletons; global state. A solution to this could be finer grained registries (As already mentioned) or dependency injection.

&lt;blockquote&gt;
The consequence of singletons and static binding is that our code does not work without the global symbol. That’s a constraint, yes, but maybe is it really so much worse than the above constraint? Our component might be so entangled with the entire application, that we don’t even think about reusing it somewhere else.
&lt;/blockquote&gt;
Put on the extreme end, you are right; What could be said about one static symbol, can be said about every static symbol. There are certainly uses for redefining a seemingly basic operator such as &lt;code&gt;+&lt;/code&gt;; Time, money, floating points and other complex types comes to mind. Generally though, I would agree that language features should be kept alone, unless there is some considerable gain to yield from replacing it. However, there is a big difference between &lt;i&gt;not redefining defaults&lt;/i&gt; and actively introducing them. What I'm advocating, is that userland code should refrain from introducing new static symbols. I would not suggest to try and "correct" the limitations of the language, using userland workarounds.

&lt;blockquote&gt;
Here I imagine some static class methods could be quite useful, to bring some order into the mess. It will still be possible to avoid using the singletons in the OOP application components.

Or not?
&lt;/blockquote&gt;
I would say that you could equally well write the bootstrapping without singletons, as you can with. They don't pose much of a problem on this level, mostly because it is already "spoiled". Eg. you can't unit-test it anyway, because of all the side-effects, so adding a singleton kind of drowns in the noise.</description>
		<content:encoded><![CDATA[<p>@fresh<br />
Those are all very good points. I&#8217;ll try to address them in sequence.</p>
<blockquote><p>
Ok, but if we pass around everything in a registry instead, then how can we know what a component does with the passed-around object? I see the same problems as before: The registry grows so big and is used in so many places, that again everything depends from everything.
</p></blockquote>
<p>That is true. There are two things that makes the registry an improvement over a singleton. The first is that it offers a flex-point; This is especially useful in testing, since it allows you to substitute a single component with a mock. The other benefit is that a single monolithic registry is the first step towards a finer grained collection of registries. You can fairly easy refactor towards having a number of registries. Eventually these registries might be possible to turn into actual objects.</p>
<p>But eventually, a registry has one of the same root-problems as singletons; global state. A solution to this could be finer grained registries (As already mentioned) or dependency injection.</p>
<blockquote><p>
The consequence of singletons and static binding is that our code does not work without the global symbol. That’s a constraint, yes, but maybe is it really so much worse than the above constraint? Our component might be so entangled with the entire application, that we don’t even think about reusing it somewhere else.
</p></blockquote>
<p>Put on the extreme end, you are right; What could be said about one static symbol, can be said about every static symbol. There are certainly uses for redefining a seemingly basic operator such as <code>+</code>; Time, money, floating points and other complex types comes to mind. Generally though, I would agree that language features should be kept alone, unless there is some considerable gain to yield from replacing it. However, there is a big difference between <i>not redefining defaults</i> and actively introducing them. What I&#8217;m advocating, is that userland code should refrain from introducing new static symbols. I would not suggest to try and &#8220;correct&#8221; the limitations of the language, using userland workarounds.</p>
<blockquote><p>
Here I imagine some static class methods could be quite useful, to bring some order into the mess. It will still be possible to avoid using the singletons in the OOP application components.</p>
<p>Or not?
</p></blockquote>
<p>I would say that you could equally well write the bootstrapping without singletons, as you can with. They don&#8217;t pose much of a problem on this level, mostly because it is already &#8220;spoiled&#8221;. Eg. you can&#8217;t unit-test it anyway, because of all the side-effects, so adding a singleton kind of drowns in the noise.</p>]]></content:encoded>
	</item>
</channel>
</rss>
