8 ms·
Google Singleton Detector
- RandallBrown 15y agoGSD 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?
- rje 15y agoFrom the usage page: * 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.
- deleted 15y ago[deleted]
- redthrowaway 15y agoThis is what happens when you let Professor Frink publish papers.
- scott_s 15y agoOr Dr. Seuss (PhD?).
- ktsmith 15y agoThey are defined in the usage wiki: http://code.google.com/p/google-singleton-detector/wiki/Usage http://code.google.com/p/google-singleton-detector/wiki/Usag... 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.
- SlyShy 15y agoIn 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/WhySingletonsAreControversial http://code.google.com/p/google-singleton-detector/wiki/WhyS...
- sebastianavina 15y agothanks for your explanation. But, what is a singleton?
- glassx 15y agoA quite good answer, from Wikipedia: "a design pattern [that restricts] the instantiation of a class to one object"
- Tiomaidh 15y agopublic 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.
- billjedi 15y agoprivate Singleton self = null; is wrong. It has to be: private static Singleton self = null;
- Jasber 15y agoAs 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?
- glassx 15y agoYMMV, but the way I prefer doing it is by telling the settings explicitly to the different classes, instead of having all those classes rely on getting it by themselves from the singleton (this is where the problem lies). 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.
- mirkules 15y agoI have been wondering the same, about other developers. 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.
- rbarooah 15y agoLetting individual classes get settings from NSUserDefaults (which itself effectively presents a singleton) directly seems to work pretty well for me. One advantage is that the classes are then reusable in other projects because they aren't coupled to an application specific settings provider.
- swah 15y agoExample of stuff that was modeled erroneously as a Singleton?
- glassx 15y agoA 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.
- czDev 15y agoAren't singletons the whole goal of Spring?
- commanda 15y agoWhat is Spring?
- btilly 15y agoSecond hit on Google: http://www.springsource.org/ http://www.springsource.org/
- brazzy 15y agoNot at all. IIRC, default instantiation mode is one instance per injection.
- czDev 15y agoActually I think singleton is the default: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-scopes http://static.springsource.org/spring/docs/3.0.x/spring-fram... I didn't know about the other scopes though
- GlennS 15y agoDependency 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.
- ecaradec 15y agoI learn how bad they were and why from this article : https://sites.google.com/site/steveyegge2/singleton-considered-stupid https://sites.google.com/site/steveyegge2/singleton-consider... That's a good read
- mikhael 15y agoI 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.
- brazzy 15y agoIf the point is to find hard-to-test code, wouldn't one find it automatically while writing tests?
- hvs 15y agoMaybe the point is to find hard-to-test code in other people's code.
- DrewG 15y agoRead Google Singularity detector. Was disappointed.
- eneveu 15y agoMisko 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/ http://misko.hevery.com/
- room606 15y agoMisko'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-pathological-liars/ http://misko.hevery.com/2008/08/17/singletons-are-pathologic... http://misko.hevery.com/code-reviewers-guide/flaw-brittle-global-state-singletons/ http://misko.hevery.com/code-reviewers-guide/flaw-brittle-gl...
- sc00ter 15y agoI was genuinely expecting a hack that parsed google+ profiles to figure out who's single... doh!
- epidemian 15y agoIsn't a "mingleton" the same as a named constructor, or am I missing something?
- misterbee 15y agoIf you mean this: http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Named_Constructor http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Named_Const... , 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 15y agoYes, I was refering to that idiom. Thanks for the clarification.
- jmitcheson 15y agoGooge Guice's documentation has a nice explanation of how to scope objects (from http://code.google.com/p/google-guice/wiki/Scopes 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 15y agoIf 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.
- statictype 15y agoshrug. 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 15y agoIt's not really a singleton if it returns an instance per session instead of a global one.
- JonnieCache 15y agoYeah, 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.
- misterbee 15y agoWhy don't you pass the session data as an argument to methods that need it?
- noduerme 15y agoSingletons 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 15y agoIn 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.
- carsongross 15y agoNow all we need is a over-engineered and inconvenient dependency injection framework detector, and we'll be all set.