15

I use a class that just extracts data from one known object, and distributes it to other known objects. No persistent configuration or such is needed in that class instance.

How should I decide whether to set up that class as a singleton, or just instantiate it every time I need it?

Peter Mortensen
  • 1,050
  • 2
  • 12
  • 14
bebbi
  • 361
  • 3
  • 8
  • 8
    Singletons are an anti-pattern (eg http://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons) and so should be avoided in such cases. – David Arno Sep 15 '15 at 09:20
  • 2
    What does "distributes it to other known objects" mean? This worries me. It sounds like you might be using this class to manage state in other places, and that smells like you might have too much state floating around. – jpmc26 Sep 15 '15 at 14:41
  • Globals are the devil, that's all you need to know! (jk) – Mark Rogers Sep 15 '15 at 18:23
  • 1
    Could this operation be a member of the single known object or of the other known objects? Why separate the logic from either of those? – Seth Battin Sep 15 '15 at 20:44
  • Does it even need to be an object? Why not a stateless function or two which you just *call* instead of *instantiate*? – Ixrec Sep 15 '15 at 23:13
  • There's not nearly enough information here to give a reasonable answer. Too broad. – RubberDuck Sep 16 '15 at 03:09
  • 1
    If you can't differentiate between the methods of the class and an instance of the class, you should be writing functions instead. It seems like this comes up every week... [Don't get class happy](http://zxq9.com/archives/877). – zxq9 Sep 16 '15 at 03:13
  • 3
    @DavidArno - calling singletons anti-pattern is cargo cult programming. – Davor Ždralo Sep 16 '15 at 08:17
  • Where does the "*one known object*" come from? – Bergi Sep 16 '15 at 09:22
  • 1
    @DavorŽdralo, that is a curious assertion indeed. Definitions of "cargo cult programming", eg https://en.wikipedia.org/wiki/Cargo_cult_programming, suggest that complete opposite: it's the blind use of singletons that fits the definition better. Either way, singletons are object-orientated global variables. As such, they have no place in modern programming practices. – David Arno Sep 16 '15 at 09:49
  • @DavidArno - that is strictly your opinion on singletons. On the other hand, nearly every large software company programming in Java uses them, so they obviously have their place. Both blind adherence to "singletons bad" and "singletons good" are cargo cults. You just seem to be in the former instead of later. – Davor Ždralo Sep 16 '15 at 09:52
  • @DavorŽdralo. The statement "singletons are object-orientated global variables" is fact. Clearly though, the view that global variables have no place in programming is an opinion, but calling it "blind adherence" is more than a little silly. It can (and has) been objectively demonstrated why global state is a bad idea, eg it makes testing far harder than it need be. – David Arno Sep 16 '15 at 09:55
  • @DavidArno - I'm calling the "singletons always bad" attitude, without explaining why, even though for example Google uses them, blind adherence. If you disagree, feel free to write a good answer explaining why singletons are *always* bad and why Google's code is full of antipatterns. – Davor Ždralo Sep 16 '15 at 09:59
  • @DavorŽdralo, please refer to the first comment above, for a link to many detailed arguments on why singletons are a bad idea. You sadly seem only able to offer an appeal to authority fallacy (large companies, eg Google use it, so it must be good) as your counter-argument. – David Arno Sep 16 '15 at 10:10
  • @DavidArno - your link is to another SO post which is even less authoritative. And is disputed right away in the first comment. Also, the whole "antipattern" thing is based on authority, to call it a fallacy now is pretty silly. – Davor Ždralo Sep 16 '15 at 10:15
  • SIngletons have a tendency to suck when things get complex, but they are often used successfully as basic constructs in some languages. – Mark Rogers Sep 16 '15 at 16:22
  • 1
    @gnat et al, I think it's misleading to mark a question "Should I choose A or B?" as a duplicate of "how to convert C to A?". It doesn't depend on some answers being similar, people google questions. – bebbi Sep 17 '15 at 06:36
  • Answering in a comment, because the question is locked. Create a caching proxy and pass it using dependency injection despite having to write tons of code. It explicitly list dependencies. – Vorac Jul 07 '20 at 08:37

4 Answers4

35

If the class has no state, you could consider turning it into a function or static method depending on your language.

JacquesB
  • 57,310
  • 21
  • 127
  • 176
  • 3
    I write a lot of 'helper methods' like this and almost always end up re-factoring them to instance methods so that I can substitute for other implementations. In this case - extracting the same data from different types of object. – Gusdor Sep 15 '15 at 15:16
  • 1
    Gusdor - To me that sounds more like a case where you want different functions, rather than different instances. They may re-use some internal more general helper function, especially if your language has first-class functions. – Jack Sep 15 '15 at 18:57
  • @Jack - In these situations, I often create an interface to be implemented on the different classes doing the extraction and then pass instances into the static method via parameter with type of the interface. Keeps the method knowing what to do with the extracted data, leaving the extraction itself to the classes who know how to do it. Writing multiple extraction methods for the different extraction types can lead to more duplicated code than necessary. – Jacob Zwiers Sep 16 '15 at 16:48
23

It is sometimes considered that the singleton is an anti-pattern. Unless the problem being solved specifically requires the use of the singleton pattern, it is generally best to avoid it.

You mention that the function would have no state or other long lived requirements, so the immediate need for an object is not there either.

A free function would be best (or static function or similar given the language and target), since it carries no state and doesn't introduce any issue associated with the singleton.

If a free function is not an option, an empty object (no data members) would probably be a close enough second option.


In general, my advice when choosing a pattern is to first understand what problem the pattern seeks to solve and what the limitations and constraints of the pattern would be. Once understood, if the problem being solved falls into that pattern's problem space then that pattern would be a candidate for use.

Niall
  • 1,831
  • 1
  • 18
  • 20
4

How do you determine what these 'known objects' are - if its hard-coded in code (ie the object is a static or singleton itself) then you might as well use a static method to perform the processing, just call that as needed.

I can't see why you'd need a whole class for this process, unless those known objects are considered state internally to the class. In this case, it depends how often you need it and the cost of constructing it, it it takes a lot of effort, a singleton is probably best.

gbjbaanb
  • 48,354
  • 6
  • 102
  • 172
4

I think the answer by Niall is good and the accepted answer is correct, but wish to add a bit in the vein of using Singletons.

The Singleton pattern is a bit like Communism. It looks good on paper, but when you mix it with people things tend to fall apart.

The thing is that the Singleton pattern isn't, inherently, an anti-pattern. It's more that most (naive) implementations of it tend to skim over important aspects or cause possible issues.

For example, in C++, a globally initialized Singleton can be allocated pretty much whenever sometime before the main loop starts. Combining multiple Singletons this way means you have no idea what order they will initialize relative to each other. The order of cleanup is similarly arbitrary (but generally the reverse of the order they were initialized in). (There are SOME basic rules for this, but mostly it's left up to the nasal demons.)

Global and readily accessible objects also tend to end up veering into the realms of a God Class, which is very much an anti-pattern. Ideas like "I already have a Manager class, I'll just stick it there," are easy and the solution is quick. This is a case of Technical Debt.

A controlled Singleton managed correctly can be very useful and not cause problems, but they are a more difficult pattern to get right than people tend to expect. The worst part is that the examples out of text books tend to teach really bad habits for Singletons.


For your specific case, since you have no state and don't need to load or unload, you don't need an object. A static function or equivalent should suit your needs.

And, since I can't comment (shakes fist), I want to second Niall's point on understanding what a pattern solves and where it works. I'd also recommend researching how it works and how best to implement it, as implementing a pattern correctly is at least as important as choosing the right pattern.

XCompWiz
  • 57
  • 4
  • Depends on the language and environment really. Obj C/Swift use singletons quite a bit. In fact, I don't know if I could live without them. I have a similar problem as OP where I have a class that asks another class to do some processing then send it to other classes. I could use a lot of boilerplate threading code and worry about deallocation of all those objects, but then I have to worry about threads crashing. Singleton works without boilerplate and memory management issues. – noobsmcgoobs Sep 16 '15 at 03:34