Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Some hold that the Singleton Pattern is always an anti-pattern. What do you think?

share|improve this question
    
Now my standard link for all discussions regarding Singletons: jalf.dk/singleton –  sbi Aug 3 '12 at 20:49
    
For now, I prefer this link for all discussions regarding Singletons. –  Cawas Nov 13 '13 at 15:46
add comment

4 Answers

up vote 14 down vote accepted

The two main criticisms of Singletons fall into two camps from what I've observed:

  1. Singletons are misused and abused by less capable programmers and so everything becomes a singleton and you see code littered with Class::get_instance() references. Generally speaking there are only one or two resources (like a database connection for example) that qualify for use of the Singleton pattern.
  2. Singletons are essentially static classes, relying on one or more static methods and properties. All things static present real, tangible problems when you try to do Unit Testing because they represent dead ends in your code that cannot be mocked or stubbed. As a result, when you test a class that relies on a Singleton (or any other static method or class) you are not only testing that class but also the static method or class.

As a result of both of these, a common approach is to use create a broad container object to hold a single instance of these classes and only the container object modifies these types of classes while many other classes can be granted access to them to use from the container object.

share|improve this answer
2  
I just would like to say that you can mock static methods in Java with JMockit(code.google.com/p/jmockit). It's a very handy tool. –  Michael K Nov 3 '10 at 14:19
3  
Some thoughts: the container is a Singleton, so you haven't gotten rid of Singletons. Also, if you're writing a library with a public API, you can't force the user of your API to use your container. If you need a global resource manager in your library (protecting access to a single physical resource, for instance) then you need to use a Singleton. –  Scott Whitlock Nov 30 '10 at 16:20
    
@Scott Whitlock why does it need to be a singleton? Just because there's only a single instance doesn't make it so. Any IoC library will manage this kind of dependency... –  MattDavey Sep 13 '11 at 8:35
    
This solution proposed it also known as Toolbox –  Cawas Nov 13 '13 at 15:06
add comment

The Singleton pattern is basically just a lazily initialized global variable. Global variables are generally and rightly considered evil because they allow spooky action at a distance between seemingly unrelated parts of a program. However, IMHO there is nothing wrong with global variables that are set once, from one place, as part of a program's initialization routine (for example, by reading a config file or command line arguments) and treated as constants thereafter. Such use of global variables is different only in letter, not in spirit, from having a named constant declared at compile time.

Similarly, my opinion of Singletons is that they're bad if and only if they are used to pass mutable state between seemingly unrelated parts of a program. If they don't contain mutable state, or if the mutable state that they do contain is completely encapsulated so that users of the object don't have to know about it even in a multithreaded environment, then there's nothing wrong with them.

share|improve this answer
1  
So in other words you are against any use of a database in a program. –  Kendall Helmstetter Gelner Jul 31 '11 at 5:53
    
There is a famous google tech talk video that echos your opinion youtube.com/watch?v=-FRm3VPhseI –  Loki Astari Mar 17 '13 at 2:01
    
@KendallHelmstetterGelner: There is a difference between state and secondary storage. It is unlikely you can hold a whole DB in memory. –  Loki Astari Mar 17 '13 at 2:04
add comment

I agree that it is an anti-pattern. Why? Because it allows your code to lie about its dependencies, and you can't trust other programmers to not introduce mutable state in your previously immutable singletons.

A class might have a constructor that only takes a string, so you think it is instantiated in isolation and does not have side effects. However, silently, it is communicating with some sort of public, globabally available singleton object, so that whenever you instantiate the class, it contains different data. This is a big problem, not only for users of your API, but also for the testability of the code. To properly unit-test the code, you need to micro-manage and be aware of the global state in the singleton, to get consistent test results.

share|improve this answer
    
Wish I could upvote more than once! –  MattDavey Sep 13 '11 at 8:37
add comment

Personally I will use singletons when I need 1, 2, or 3, or some limited amount of the objects for the particular class in question. Or I want to convey to the user of my class that I do not want multiple instances of my class being created for it to function properly.

Also I will only use it when I need to use it almost everywhere in my code and I don't want to pass an object as a parameter to each class or function that needs it.

In addition I will only use a singleton if it does not break another function's referential transparency. Meaning given some input it will always produce the same output. I.e. I don't use it for global state. Unless possibly that global state is initialized once and never changed.

As for when not to use it, see the above 3 and change them to the opposite.

share|improve this answer
1  
-0 but i nearly -1. I would rather pass it everywhere in my code instead of use a singleton BUT if i am really lazy i may do that. I'd use global vars instead if i am able to or static members. global vars are really much preferable (to me) then singletons. Globals dont lie –  acidzombie24 Dec 6 '10 at 13:15
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.