multipart-message nevyn bengtsson's blog

featured articles 🦄, about, archive, tags

Nevyn's First Rule of Singleton Evilness

I finally figured out a litmus test for whether being a singleton is okay or evil for a particular class:

If a class is thread-safe and has no state that can be changed, it may be a singleton.

NSFileManager: OK. RMS::Sound::Gateway: Not so much.

I suppose there are ways to circumvent this rule; e g most of Apple’s singletons may be created either through the+[defaultManager] method, or instantiated on-the-spot, e g if you want several separate NSNotificationCenter inside the same application.

This discussion came up during the creation of the RMS game engine, among many other times. Now that I’m ripping out parts of the engine for re-use, I realize that it was a very bad design decision to use singletons the way we did. For example, my 2D modeler prototype for my candidate thesis is document-based, thus it needs an RMS::Sound::Gateway for each window. This is no-can-do until I fix the code, because for example the Voice class has the delegated play method, and the way it works is that it gets the global gateway and adds itself to the gateway’s list of playing voices.

“State that can be changed”? Oh, right. +[NSColor redColor] has state, but it can still be a singleton since that state can’t be changed by my code. Same for NSEvent’s singleton methods, and so on.

Tagged coding, faves