
Google Singleton Detector - jamesjyu
http://code.google.com/p/google-singleton-detector/
======
SlyShy
In case you are wondering why singleton's are bad practice in Java, here are
two reasons off the top of my head.

1) Dependency hiding.

Singletons are rarely based around as parameters. Rather, methods simply
access and modify them as necessary. This can be obviously convenient in a lot
of places, but it makes looking at method signatures less reliable a way of
determining dependencies.

2) Global state.

Singletons are global state, more or less, and are thus difficult to maintain.
Bugs involving global state can be hard to detect, and global state isn't even
amenable to testing, because the order of your tests start to matter. Side-
effects bring a lot of troubles.

Edit: I guess this is redundant with the information on this page.
[http://code.google.com/p/google-singleton-
detector/wiki/WhyS...](http://code.google.com/p/google-singleton-
detector/wiki/WhySingletonsAreControversial)

~~~
yuvadam
My gripe with global state (i.e. singletons) is not testability,
maintainability nor correctness. It's nothing more than bad object-oriented
design, or lack thereof.

I've seen this time and again - even this week, as I am doing some major
refactoring in old code - singletons are used exactly where someone was too
lazy (or too busy) in order to do a proper design and review. I cannot count
the number of proverbial _SomethingManager_ singleton classes I've seen.

At most, singletons should be used in a single point of entry to a module.
From there on, even if other classes should be used once, their singularity
will be derived from that single point of entry that contains them.

Rule of thumb - stop using singletons. In 99% of the cases you will see a much
better design exists.

~~~
Zak
Calling something bad design without discussing the actual problems it causes
is mere name-calling or unsupported opinion. I submit that if you can't make a
claim that something is hard to maintain, unreliable, hard to understand,
incorrect, fragile, etc... then it is _not_ bad design.

The claim that it is "bad" because it doesn't fit in to a certain paradigm is
at best a valid claim that it is inconsistent with the rest of the codebase
and therefore hard to work with. At worst, it's cargo-cult engineering; doing
something a certain way because it's said to be "good" without understanding
why.

~~~
nostrademons
"I submit that if you can't make a claim that something is hard to maintain,
unreliable, hard to understand, incorrect, fragile, etc... then it is not bad
design."

That's not really true either - it just means that the claimant probably lacks
the experience to recognize whether or not it's bad design. Even people who
are right for the wrong reasons can still be right.

~~~
Zak
That's a valid point, but in that case the claim is no more reliable than
random chance.

------
Jasber
As a new Objective-C programmer, I recently ran into the global state problem
with an iPhone game I'm working on. I needed some settings that could be
accessed/changed from many different classes. I was told the AppDelegate isn't
the right place to put this.

A singleton SettingsManager was suggested, but singletons always get a bad
wrap.

So is this a good use of a singleton? What would be the correct way to handle
this?

~~~
ardit33
hey Jaber. Singletons are fine for that purpose, actually they are probably
the best solution.

iOS uses singletons everywhere, so feel free to use them.

Don't fall the trap of the cargo culture thinking. Google has a completely
different problem than you do. Their code spans hundreds of thousands (or
millions), of code, in distributed systems, etc..

your iOS app probably has different constrains.

~~~
hoopadoop
Where does IOS use Singletons?

~~~
rbarooah
Depends on your definition of singleton.

In java, singletons are enforced by the type system - i.e. There's no public
way to make more of the object. Usually that's what people mean by 'singleton'
in java. If you don't have the source and you outgrow the single instance,
there's nothing you can do except stop using the class.

In Objective-C, people do occasionally simulate that by mungng init and alloc,
but that is definitely a bad idea. More often a singleton class will have a
conventional init and alloc, but have a class method like +sharedInstance
which lazily instantiates and dispenses a single instance of the object during
the lifetime of the application. That's what people most often mean by
'singleton' in objective-c. It's basically a global variable, but when you
outgrow it, it's often not hard to switch to allocating more than one.

Also, partly due to what many would see as a deficiency - the fact that it's
much harder to produce architecture independent libraries in objective-c than
java, the source is available more of the time, so evolving past a singleton
is more often straightforward.

------
RandallBrown
GSD doesn't only detect singletons; it detects four different types of global
state, including singletons, hingletons, mingletons and fingletons

uhh, what are hingletons, mingletons and fingletons?

~~~
ktsmith
They are defined in the usage wiki: [http://code.google.com/p/google-
singleton-detector/wiki/Usag...](http://code.google.com/p/google-singleton-
detector/wiki/Usage)

    
    
      Singleton	 A class for which there should only be one instance in the entire system at any given time. This program detects singletons which enforce their own singularity, which means they keep one static instance of themselves and pass it around through a static getter method.
    
      Hingleton	 Derived from “helper singleton,” a class which turns another class into a singleton by enforcing that class's singularity.
    
      Mingleton	 Derived from “method singleton” a class which has any static method that returns some state without taking any parameters.
    
      Fingleton	 Derived from “field singleton,” a class which contains a public static field.

~~~
chancho
So, GSD is just "grep -r static . | grep -v class" then?

~~~
carbonica
It operates on JVM bytecode, not on java source code.

------
eneveu
Misko Hevery - one of the developers of the GSD - has a blog were he talks
about testing, dependency injection, and global state. He hasn't posted a lot
recently, but there is a lot of interesting stuff if you dig through his
archive.

<http://misko.hevery.com/>

~~~
room606
Misko's blog is brilliant and it is truly a shame he isn't posting as much as
he used to

Some posts relevant to this discussion

[http://misko.hevery.com/2008/08/17/singletons-are-
pathologic...](http://misko.hevery.com/2008/08/17/singletons-are-pathological-
liars/)

[http://misko.hevery.com/code-reviewers-guide/flaw-brittle-
gl...](http://misko.hevery.com/code-reviewers-guide/flaw-brittle-global-state-
singletons/)

------
ecaradec
I learn how bad they were and why from this article :

[https://sites.google.com/site/steveyegge2/singleton-
consider...](https://sites.google.com/site/steveyegge2/singleton-considered-
stupid)

That's a good read

~~~
mikhael
I have seen this article referenced rather often, and I really have a problem
with it. Despite being called "Singleton Considered Stupid," much of the
article is not about singletons at all, and he barely addresses why singletons
are bad. The actual arguments, buried 3/4 of the way into the article, boil
down to a) resource/memory management problems, and b) that in the future, you
might possibly need more than one object of anything you decide to make a
singleton. (He mentions multithreading too, but that is just silly; e.g. even
if I had multiple Log objects, there would need to be synchronization at some
point if I'm outputting to the same stream). He writes numerous times that
it's bad OOP, or "OOP made easy," because it is too much like procedural
programming, but only mentions the factory-method pattern as an alternative at
the very end of the article, and doesn't actually say WHY it's better. The
necessity for, or at least temptation of global state is not even mentioned.

------
jmitcheson
Googe Guice's documentation has a nice explanation of how to scope objects
(from <http://code.google.com/p/google-guice/wiki/Scopes>). How they word it
is specific to Guice but the underlying points are valid for any Java
application

"Choosing a scope

If the object is stateful, the scoping should be obvious. Per-application is
@Singleton, per-request is @RequestScoped, etc. If the object is stateless and
inexpensive to create, scoping is unnecessary. Leave the binding unscoped and
Guice will create new instances as they're required.

Singletons are popular in Java applications but they don't provide much value,
especially when dependency injection is involved. Although singletons save
object creation (and later garbage collection), getting a handle to the single
instance requires synchronization. Singletons are most useful for:

* stateful objects, such as configuration or counters

* objects that are expensive to construct or lookup

* objects that tie up resources, such as a database connection pool."

I have to admit that when I first started coding Java/Guice I had 'singleton
addiction'. Luckily with Guice, as someone else mentioned, it's just matter of
deleting the annotation on a class to change your mind about that.

Anyway, if you use Guice and dependency inject your singleton classes, then
the issue of being hard to test and disguising dependencies goes away, doesn't
it?

~~~
misterbee
If you use Guice you aren't using a singleton anymore. Guice is creating an
instance and passing it to multiple classes as a dependency. This is different
from any class just referencing a Singleton by importing it statically.

It's a slightly subtle distinction, and you still have the risks associated
with non-local mutable objects, but at least you can track (using the
Annotation API) which classes are using the shared state; it's better than
letting any line of code anywhere in the middle of any method sneakily and
suddenly grab access to shared state.

------
sc00ter
I was genuinely expecting a hack that parsed google+ profiles to figure out
who's single... doh!

------
statictype
_shrug_. I've found singletons to be good for modelling session data in a web
server.

Calling GetInstance returns the object stored in the session, creating a new
empty one and stashing it there if required.

That's actually, pretty much the only thing I use them for, though.

~~~
TwoSheds
It's not really a singleton if it returns an instance per session instead of a
global one.

~~~
JonnieCache
Yeah, its not really at true singleton in the dangerous sense in the context
of a webserver, when you have a separate copy of the environment for each HTTP
connection. It wouldn't be a singleton unless the same state could be accessed
by different HTTP sessions.

I haven't come across a web framework that enables this, as you might expect;
there's no good reason to do so.

------
brazzy
If the point is to find hard-to-test code, wouldn't one find it automatically
while writing tests?

~~~
hvs
Maybe the point is to find hard-to-test code in _other_ people's code.

------
swah
Example of stuff that was modeled erroneously as a Singleton?

~~~
glassx
A personal example.

Just when I started college, was trying to write a 3D game in C++ (I was
young, so yeah, I thought it was just C with classes, LOL).

Since I had no idea about design patterns, so I made a singleton called
"Rendering Manager" that took care of "everything-OpenGL". I would have
numerous classes, like CHuman, CHero, CParticle, CBuilding (it was more
abstract but whatver) and stuff like that that inherited from something like a
CDrawable, which had a CDrawable::Render() method.

The problem was that the CDrawable::Render() would call the singleton by
itself, so it had a direct dependency with the Rendering Manager. If I had to
change something on the singleton, I'd have to change a lot of other classes.

When I needed to render on different "virtual screens", for reflections,
shadows, cameras (yes, it was funky lol), I had to put global state on the
singleton in order to make it render things in different ways.

When I needed LOD (level of detail), I had to pass the camera position via a
global, only adding more globals to the mess.

Of course, I was just a student back then, but failing spectacularly taught me
a lot of new things.

\--

What I would have done today: CDrawable objects would only worry about their
own geometry and transformations and would be ignorant about the glorified-
OpenGL-wrapper.

Instead, we could have a "Scene Manager" (which doesn't even have to be a
singleton anymore) that "visits" each object to "ask" them just enough to get
them rendered.

------
carsongross
Now all we need is a over-engineered and inconvenient dependency injection
framework detector, and we'll be all set.

------
epidemian
Isn't a "mingleton" the same as a named constructor, or am I missing
something?

~~~
misterbee
If you mean this:
[http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Named_Const...](http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Named_Constructor)
, which is called a Factory, in Java, then no.

A Named Constructor / Factory creates a new instance on demand. A mingleton
hands out references to the same instance each time it is called.

~~~
epidemian
Yes, I was refering to that idiom. Thanks for the clarification.

------
DrewG
Read Google Singularity detector. Was disappointed.

------
czDev
Aren't singletons the whole goal of Spring?

~~~
GlennS
Dependency injection frameworks/IOC containers (pick your stupid name of
choice) avoid at least one of the problems of singletons: if you decide that
you don't want it to be a singleton any more, you can trivially change the
lifecycle to 'instance'.

By contrast, using singletons in plain old Java, you'd have to go through and
find every usage of SingletonClass.instance().everyMethodCallOnThisClass() and
push it up to the constructor. Since you now have a new dependency you have to
pass all the way down your callstack, it can get painful quickly.

You still have the issue of global state, but I think that's altogether more
complicated. Sometimes state really is global to your program and exposing it
everything makes a certain amount of sense. It may well be ok for managing
system resources (thread pools, network connections, IO in general). I think
often you can get away with a boolean flag or two shared across a whole app.
If it's read-only it's not a problem at all.

You need to be aware that every bit of shared state you make available or
continue to use is a potential source of bugs and maintenance. Every bit of
this that you expose needs serious thought. Don't let it snowball. Even if it
means you have to make a few extra types of object or pass a stupid number of
arguments all the way down the callstack, that's usually preferable because at
least then you can reason about what's going on.

~~~
misterbee
And with structured programming, it's only one extra argument per function
call, StuffThisFunctionNeeds (plus a structure definition for each different
flavor of StuffThisFunctionNeeds)

------
noduerme
Singletons are great for some things, and not bad design at all. Font
managers, sound managers, upload managers, focus managers, anything that
starts and stops threads are all good candidates for them. Singletons are an
obvious solution for any program that needs to round-robin users to one of
many nodes upon login and then leave them there for all classes to communicate
with. Especially if you might need all your classes to suddenly start talking
to a different server node instead. There's no reason -- and it's possibly
dangerous -- to create multiple instances of any of the above...and the
ability to (for instance) globally alter the volume of all the sounds of a
given type in your game, or call a static function to play any sound, far
outweighs the supposed design beauty of OO in those cases. In fact, you could
argue that OO code only really works because it relies on a single instance of
the system it's running on to manage one or more threads, one or more sound
channels through a single set of speakers, etc.

If common sense would dictate that there should never be more than one
instance of something, then enforcing that becomes good design, the equivalent
of writing good docs and clean virtual classes / interfaces.

~~~
rojoca
In my experience I have found that explicitly passing your dependencies around
through constructors or method arguments leads to more robust abstractions.
Defining an object as a Singleton from the get-go can lead to its overuse.

If you have to pay the cost of adding a parameter to a method or a constructor
you really evaluate whether you need that object in that method in the first
place. This doesn't stop you from enforcing a single instance.

