Google Singleton Detector
code.google.com
code.google.com
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...
"a design pattern [that restricts] the instantiation of a class to one object"
public class Singleton {
private static Singleton self = null;
private Singleton() {
//...
}
public static Singleton getInstance() {
if(self == null) {
self = new Singleton();
}
return self;
}
...
}
So at any point in your code you can call Singleton.getInstance() to have access to the same Singleton object. So it's effectively the same thing as a global variable.Edit: Added `static' to be more correct.
It has to be:
private static Singleton self = null;
it's surprisingly tricky to get lazy init right.
The only reason to use a singleton over static members is that it feels like OO. I suppose it also makes it easier to replace the singleton with a 'multiton' at some point in the future which somewhat justifies it.
In Java/C# you can use a nested class to ensure thread safety and cheat towards having your static methods. For example:
private int Foo() { }
public static int Foo() { return _instance.Foo(); }
private static FooBar _instance { return Nested.instance; }
FooBar() { // Initialize here! }
class Nested {
static Nested() { }
internal static readonly FooBar instance = new FooBar();
}
public enum Singleton {
INSTANCE;
}
Guaranteed against multiple instantiation.Edit: the class version of the singleton example should also be made final, or I could just extend your class and therefore bypass your singleton restriction.
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.
In general, whether we are talking about procedural, OO, functional, or whatever kind of programming, code is easier to reason about and test and use if the effects of its individual units (functions, classes, modules, &c.) depend largely on the inputs to them. In functional languages this is called "referential transparency," but its value applies to OOP as well.
Using things like singletons creates hidden dependencies on things that can change over the lifetime of the program without those changes being made obvious to clients of that unit of code. Good design nails things down to explicit parameters.
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.
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.
So, you have an app deployed to seven customers. The typical pattern is you develop an app for a first customer. It is then sold to subsequent customers, doing the least possible to make it work. In this case, as I have seen in the past, you have a properties file, saying which classes to use and which configuration options the customer has available.
These are then loaded up, as global state, so that your code can ask, "Does this application have Widget Processing capabilities?" and gets the answer for its code path. Consider:
if (AppProperties.getInstance().hasWidgetProcessing() {
process(widget);
}
Now, the problems here are pretty obvious. Since you're depending on a single file, your testing is a bear. Getting to the various codepaths is nigh impossible. Ideologically, it's bad design because your software has a bunch of if or switch statements in the code to decide what it should really do.Now, what would make this code better? Well, you could start with taking all your Widget Processing capabilities and putting them in their own object or package. Then, instead of the above, your code looks like this:
public class WidgetImpl implements Widget {
private WidgetProcessor widgetProcessor;
public void process() {
widgetProcessor.process(this)
}
public void setWidgetProcessor(WidgetProcessor wp) {
this.widgetProcessor = wp;
}
}
In your main code: widget.process();
WidgetProcessor has two (or more) implementations, in this case: RealWidgetProcessor and NullWidgetProcessor. NullWidgetProcessor just returns without doing anything.
Now, how does your Widget get the proper widget processor? Dependency injection. http://code.google.com/p/google-guice/wiki/Motivation?tm=6 has a pretty good explanation.Improvements on the design are welcomed, as always. :) Though for simplicity's sake I was trying to keep code to a minimum. Now, speaking of code, my main issue with dependency injection is that the code baloons, especially in java. DI as a pattern makes me feel like there's something missing in current language implementations that would make this more elegant. Aspect-oriented programming was one try at it, but it seems that the cure is worse than the disease in that case.
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?
You can pass the settings in the constructors, with setter methods or have a "state object" that contains the configuration.
For "updating" the states on every class in real time I'd rather rely on explicit state change using the Observer pattern.
EDIT: I'd also like to know what other developers do, or if there's anything wrong with my methods, so I second your question.
I am working on an application that periodically pulls information from a server about a physical object (sorry, I can't be more specific than this, so please don't ask). This information needs to be accessed by several different classes, and displayed in view controllers on different tabs. A view controller will pull the information and make it available to all the other view controllers.
A singleton provided an effective solution to this because only one data model of my physical object's state can exist at any given time, with the added benefit that I can access it from any view controller without much effort.
I may be wrong, but I thought the purpose of a singleton was for models where there can be one and only one instance of your class? Singletons (like other design patterns) were designed to solve a specific problem. But I concede that they are probably overused.
One advantage is that the classes are then reusable in other projects because they aren't coupled to an application specific settings provider.
Hopefully this will stem the tide of questions on Stack Overflow about different Objective-c singleton implementations.
I'm also interested in hearing what is considered the best practice for things like passing around config options, an eventloop, or message bus.
When you DO need global state, then a singleton object is a reasonable way to achieve it. But chances are fairly high that you don't.
As I'm not in the mobile sphere, I wouldn't know how to avoid a singleton for an app that is constrained by speed and space requirements. I've already shown an example above, what's your solution in this environment, with the constraints of the questioner?
If he's making a game, this is completely acceptable design. Games programming is wildly different from application or server programming. Also, strict TDD is much, much less useful in games programming than anywhere else. Writing unit tests for central data structures and algorithms is useful, of course, but the majority of modules/classes/objects are so small, uncritical, and change completely so often that it's not worth bothering.
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.
http://developer.apple.com/library/ios/#documentation/uikit/...
It is almost everwhere.
[MyClass sharedMyclass] is the Objective-C equivalent of getInstance()
Also, singletons make good sense in mobile apps, as it is a very different type of a beast than a server side app.
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.
This is probably the single most useful quote in this entire discussion. Singletons are not inherently bad -- they were created for a reason, but because people abuse them, they have a bad rep.
I would go as far as to say that if you have to do multiple "application runs" in the same "test run", where these "application runs" require different configurations to have the test cover some specific scenario, then your code has larger problems than having the configuration in a singleton.
uhh, what are hingletons, mingletons and fingletons?
* 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. 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.Some posts relevant to this discussion
http://misko.hevery.com/2008/08/17/singletons-are-pathologic...
http://misko.hevery.com/code-reviewers-guide/flaw-brittle-gl...
https://sites.google.com/site/steveyegge2/singleton-consider...
That's a good read
"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?
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.
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.
I haven't come across a web framework that enables this, as you might expect; there's no good reason to do so.
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.
A Named Constructor / Factory creates a new instance on demand. A mingleton hands out references to the same instance each time it is called.
I didn't know about the other scopes though
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.
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.
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.