The Artima Developer Community
Sponsored Link

Weblogs Forum
Singleton Considered Harmful?

34 replies on 3 pages. Most recent reply: Sep 17, 2007 3:20 PM by Marco Dorantes

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 34 replies on 3 pages [ 1 2 3 | » ]
Bruce Eckel

Posts: 875
Nickname: beckel
Registered: Jun, 2003

Singleton Considered Harmful? (View in Weblogs)
Posted: Aug 27, 2007 5:52 AM
Reply to this message Reply
Summary
In Java Posse #136, the Posse discusses the Google Singleton Detector which automatically discovers singletons in your code and they all agree that singletons are a bad idea.
Advertisement

Here is the link to the show notes.

This is the kind of thinking that Java seems to promote for some reason: there's one right answer that you should apply everywhere. It's certainly comforting to think that someone out there is being "the decider" and that you only need to follow those decisions without question. Another place I've seen this is in the cult of "interfaces everywhere," in which you mindlessly create an interface for every class in case, I suppose, you ever need it. Also, the attitude that more static type checking will fix every problem that we discover.

Design patterns are design choices that arise out of need. Clearly, using a singleton as just another global variable is a bad idea, but does this make singleton itself a bad idea? Sometimes you need a "single point of truth," a registry where you go to get information that is used universally. This isn't a casual choice, but it happens, and when it does a knee-jerk reaction that says singletons are bad is not going to help. Even Dijkstra's famous "goto considered harmful" that has been the genesis of these kinds of diatribes is qualified -- he was talking about unconstrained gotos, otherwise Java's labeled break and labeled continue would be considered "bad."


James Watson

Posts: 2024
Nickname: watson
Registered: Sep, 2005

Re: Singleton Considered Harmful? Posted: Aug 27, 2007 6:17 AM
Reply to this message Reply
I've seen a lot of code where instance of pretty much every class was retrieved through Singletons. I think the previous insane popularity of Singletons has resulted in this backlash.

Bruce Eckel

Posts: 875
Nickname: beckel
Registered: Jun, 2003

Re: Singleton Considered Harmful? Posted: Aug 27, 2007 6:46 AM
Reply to this message Reply
I like the idea of a tool that points them out to you so that you can evaluate whether they are appropriate. But the key is design, and they are occasionally appropriate. Just saying "singletons are all bad" is no different than using them everywhere. Neither is a design decision.

James Watson

Posts: 2024
Nickname: watson
Registered: Sep, 2005

Re: Singleton Considered Harmful? Posted: Aug 27, 2007 7:03 AM
Reply to this message Reply
> I like the idea of a tool that points them out to you so
> that you can evaluate whether they are appropriate. But
> the key is design, and they are occasionally appropriate.
> Just saying "singletons are all bad" is no different than
> using them everywhere. Neither is a design decision.

I agree completely. I always say that rules of thumb are not a replacement for understanding and being able to think.

But I have to say, I prefer the current dogma to the old dogma. On the other hand, I don't see a lot of value in the Singleton detector. If the Singletons are causing problems then they will(hopefully) be detected. If they are not causing issues, then who cares?

Toby Ho

Posts: 4
Nickname: airportyh
Registered: Jun, 2006

Re: Singleton Considered Harmful? Posted: Aug 27, 2007 8:01 AM
Reply to this message Reply
> <p>This is the kind of thinking that Java seems to promote
> for some reason: there's one right answer that you should
> apply everywhere.

Ditto on that.

> Another place I've seen this is in the cult of
> "interfaces everywhere," in which you mindlessly
> create an interface for every class in case, I suppose,
> you ever need it.

Ditto on that too. This sort of thing in the Java community drives me crazy. I think it's just promotes mindlessness and encourages programmers to be dumb, and therefore commoditizing the programming profession.

Michael Barker

Posts: 5
Nickname: mikeb01
Registered: Oct, 2005

Re: Singleton Considered Harmful? Posted: Aug 27, 2007 11:33 AM
Reply to this message Reply
One of the problems with the Singleton is that it is heavily overused. I have just started on a project that is struggling in its final phases. The entire code base is littered with Singletons making it difficult to introduce badly needed unit tests as the Singletons have introduced a hard wiring of dependencies between classes.

What I would like to see is a really good use case for Singletons that can't be solved using some form of dependency injection.

> Sometimes you need a "single point of truth," a registry
> where you go to get information that is used universally.

That is true, but is a Singleton the best solution for this problem? A Singleton in Java is not guaranteed to provide a single point of truth. E.g. an application that happens to span multiple EAR files will have multiple instances of the Singleton class as they will be loaded in different classloader hierarchies (or you may get a single instance depending on the Application Server). Clustering also are a source of pain in this area. Perhaps this problem can be solved using pre-existing solutions, e.g. the concept of a registry could be address using JNDI or MBeans.

I wouldn't suggest that the Singleton pattern should be abandoned altogether, but those designing software should assess whether a Singleton is really appropriate. I would ask the following questions. 1. Is it appropriate to hard wire my application to this class? 2. Can I easily unit test code that uses this class? 3. Is my Singleton thread-safe? 4. Can my application deployment result in multiple instances of this Singleton and what are the side effects of that occurring? 5. Are there any better solutions?

Mike.

James Watson

Posts: 2024
Nickname: watson
Registered: Sep, 2005

Re: Singleton Considered Harmful? Posted: Aug 27, 2007 12:20 PM
Reply to this message Reply
> One of the problems with the Singleton is that it is
> heavily overused. I have just started on a project that
> is struggling in its final phases. The entire code base
> is littered with Singletons making it difficult to
> introduce badly needed unit tests as the Singletons have
> introduced a hard wiring of dependencies between classes.

This is one of the biggest problems with the Singleton pattern. Even though it's so often used, it's generally misunderstood.

Properly implemented, the Singleton pattern should not 'hardwire' classes together. The most overlooked part of the Singleton pattern is that the GoF description includes the ability to subclass the Singleton. For example, in your testing example, Singletons, when configurable, can actually be a easy place to insert mocks and stubs for dependencies of a class. The way most Singletons are implemented does not allow for that.

The main reason I see for the lack of Singletons that can be subclassed in Java is that far too much emphasis is given to the 'uniqueness' of the singleton. If you want to protect the Singleton from multiple instances you need a private constructor. I've never really run into a situation where a truly single Singleton was really required and as you point out, this isn't possible in Java for the general case.

The real problem is the overuse of global objects and people only half-understanding what they have read.

David Linsin

Posts: 9
Nickname: dlinsin
Registered: Aug, 2007

Re: Singleton Considered Harmful? Posted: Aug 27, 2007 12:40 PM
Reply to this message Reply
I think we all do agree on that there is no right answer for this question. But what I'm asking myself is, where is the right place to apply a Singelton?

When you model your domain or business, would you consider using a Singleton? To me it seems like a Singelton is more of a technical aspect. So when do you guys think a Singleton is the right choice?

James Watson

Posts: 2024
Nickname: watson
Registered: Sep, 2005

Re: Singleton Considered Harmful? Posted: Aug 27, 2007 12:59 PM
Reply to this message Reply
> I think we all do agree on that there is no right answer
> for this question. But what I'm asking myself is, where is
> the right place to apply a Singelton?
>
> When you model your domain or business, would you consider
> using a Singleton? To me it seems like a Singelton is more
> of a technical aspect. So when do you guys think a
> Singleton is the right choice?

I think it's good for when you want a shared object. A classic example is a local cache. A lot of people say that DI makes Singleton unnecessary and they may be right but DI containers seem to be the current one-size-fits-all solution. I'm not convinced it will never fall out of favor. If this isn't correct and DI containers are the ultimate future of programming, then we should be looking at pulling it out of XML and formalizing it as a general purpose programming language.

Andreas Nilsson

Posts: 1
Nickname: trialcode
Registered: Oct, 2006

Re: Singleton Considered Harmful? Posted: Aug 27, 2007 2:28 PM
Reply to this message Reply
I'd say singletons indicate failure to decide who owns the object. You say singleton Registry, I say put it in the Application object or create an Application class if one doesn't exist. If you consistently apply this routine all the way out to main() (where you'd create the single needed Application object in this case) you don't ever need singletons.

The other problem that singletons "solve" is global access. Just resist the temptation and pass the damn object as a parameter to the objects (via the constructor) and functions that need it. Pretending that tough decisions don't exist doesn't make them go away. To go back to the Registry example, say you want to create a Window that needs access to the Registry:

Window Application#createWindow() {
return new Window(this);
}

The Window can then access the registry via f.ex. 'application().registry()'.

Anthony Williams

Posts: 3
Nickname: anthonyw
Registered: Aug, 2007

Re: Singleton Considered Harmful? Posted: Aug 27, 2007 3:55 PM
Reply to this message Reply
> > One of the problems with the Singleton is that it is
> > heavily overused. I have just started on a project
> that
> > is struggling in its final phases. The entire code
> base
> > is littered with Singletons making it difficult to
> > introduce badly needed unit tests as the Singletons
> have
> > introduced a hard wiring of dependencies between
> classes.
>
> This is one of the biggest problems with the Singleton
> pattern. Even though it's so often used, it's generally
> misunderstood.
>
> Properly implemented, the Singleton pattern should not
> 'hardwire' classes together. The most overlooked part of
> the Singleton pattern is that the GoF description includes
> the ability to subclass the Singleton. For example, in
> your testing example, Singletons, when configurable, can
> actually be a easy place to insert mocks and stubs for
> dependencies of a class. The way most Singletons are
> implemented does not allow for that.

True, singletons can be written to be configurable, which does facilitate testing, but they're still "hidden" dependencies. By that I mean that the dependency is an implementation detail, which is retrieved by the class itself.

> The main reason I see for the lack of Singletons that can
> be subclassed in Java is that far too much emphasis is
> given to the 'uniqueness' of the singleton. If you want
> to protect the Singleton from multiple instances you need
> a private constructor. I've never really run into a
> situation where a truly single Singleton was really
> required and as you point out, this isn't possible in Java
> for the general case.

Yes. I think Singleton is the wrong way to implement uniqueness.

> The real problem is the overuse of global objects and
> people only half-understanding what they have read.

Agreed. A Singleton typically is a global variable, though.

> I think it's good for when you want a shared object. A
> classic example is a local cache. A lot of people say
> that DI makes Singleton unnecessary and they may be right
> but DI containers seem to be the current one-size-fits-all
> solution. I'm not convinced it will never fall out of
> favor. If this isn't correct and DI containers are the
> ultimate future of programming, then we should be looking
> at pulling it out of XML and formalizing it as a general
> purpose programming language.

I'm not a big fan of DI using external XML. Instead, I prefer to pass in the required collaborators as constructor parameters to each class, using factory functions where necessary. This puts the key information about which classes are actually used in the application in the code itself --- at the top level, the "main" function.

If you do this, then singletons do become unnecessary --- if you need only one instance, you only create one, and pass it around. Also, this greatly facilitates testing, as you can freely pass in subclasses or alternative implementations of the interface as necessary.

Roger Voss

Posts: 27
Nickname: rogerv
Registered: Aug, 2005

Re: Singleton Considered Harmful? Posted: Aug 27, 2007 9:03 PM
Reply to this message Reply
Obviously a singleton that is initialized and then remains invariant during it's life-cycle of use is fine as there is then no thread blocking contention for accessing it. (It's read-only so no thread need wait on a lock in order to access it.)

The serious complaints about singletons have centered around the drawback of thread contention.

David Linsin

Posts: 9
Nickname: dlinsin
Registered: Aug, 2007

Re: Singleton Considered Harmful? Posted: Aug 27, 2007 9:46 PM
Reply to this message Reply
> I'd say singletons indicate failure to decide who owns the
> object. You say singleton Registry, I say put it in the
> e Application object or create an Application class if one
> doesn't exist. If you consistently apply this routine all
> the way out to main() (where you'd create the single
> needed Application object in this case) you don't ever
> need singletons.
>
> The other problem that singletons "solve" is global
> access. Just resist the temptation and pass the damn
> object as a parameter to the objects (via the constructor)
> and functions that need it. Pretending that tough
> decisions don't exist doesn't make them go away. To go
> back to the Registry example, say you want to create a
> Window that needs access to the Registry:
>
> Window Application#createWindow() {
> return new Window(this);
> }
>
> The Window can then access the registry via f.ex.
> 'application().registry()'.

Isn't this the notion of DI what you describe?

I totally agree on passing objects by method/constructor parameters, instead of having a Singelton. But I also have to admit that it's sometimes very tempting to just use a Singelton.

Brian Slesinsky

Posts: 43
Nickname: skybrian
Registered: Sep, 2003

Re: Singleton Considered Harmful? Posted: Aug 27, 2007 11:48 PM
Reply to this message Reply
Singletons aren't really about uniqueness; they're about enforcing a one-to-one mapping between a classloader and an instance, or in the simple case where there's only one classloader, it's one-to-one between the instance and the JVM. The situations in which you need that particular one-to-one-mapping are a lot rarer than people think.

More likely, what you really want is a one-to-one mapping between the instance and an instance of your application. But it should still be possible to start and stop multiple instances of your app within the same JVM (for example in the same test suite). Preventing this means that to test your app properly, you have to start a whole different process.

This probably wouldn't be a big deal if starting up a new JVM with the same classpath were easier, or classloaders weren't so hairy to deal with, but in the language we have, avoiding direct ties between the number of apps running and the number of JVM's running is the most flexible way to code.

Achilleas Margaritis

Posts: 674
Nickname: achilleas
Registered: Feb, 2005

Re: Singleton Considered Harmful? Posted: Aug 28, 2007 3:26 AM
Reply to this message Reply
Singletons are global variables...so if they are overused, the program becomes spaghetti.

Flat View: This topic has 34 replies on 3 pages [ 1  2  3 | » ]
Topic: Singleton Considered Harmful? Previous Topic   Next Topic Topic: Quoted in CNN's Business 2.0

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use