12

Lately there have been some kind of revolution against singletons, but is there something wrong with them if they are stateless?

I know the overuse talk and all... this applies to everything not just singletons.

Random42
  • 10,370
  • 10
  • 48
  • 65
  • 1
    No. Singletons are in principle not bad, they are just massively overused. – Bart van Ingen Schenau Jan 04 '13 at 10:22
  • A stateless singleton still suffers an important problem of singletons: it can't easily be replaced for testing. – Joachim Sauer Jan 04 '13 at 10:28
  • 3
    what do you mean by Lately? – Manoj R Jan 04 '13 at 10:54
  • 6
    @Joachim Sauer: Why would you need to replace; if it is stateless you can test it dirrectly. – Random42 Jan 04 '13 at 11:06
  • 1
    If you have stateless singleton then you basically have a static utility class, which has a tendency of growing into the God Class anti-pattern. You can usually use static methods instead in the context they're used in (or even better: use extension methods in C#). – Spoike Jan 04 '13 at 11:18
  • It is not bad, to the point that Scala has a keyword for it (`object`) and that these objects are the basis of Scala's module system – Andrea Jan 04 '13 at 11:19
  • http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/ – Robin Winslow Jan 04 '13 at 13:05
  • @Robin Winslow That article doesn't say anything about stateless/immutable singletons; it only mentions about this in a comment which approves them. – Random42 Jan 04 '13 at 13:50
  • Duplicate of http://programmers.stackexchange.com/questions/252/when-is-singleton-appropriate; see dsimcha's answer. – Aaron Kurtzhals Jan 04 '13 at 15:37
  • @Spoike: I don't think so. If it's stateless, it can't be a God *Object*. One instance, that never changes, is equivalent to static data. – Steven Evers Jan 04 '13 at 16:53
  • @SnOrfus: Please notice I called it a God *Class*, not Object. Nevertheless, it is still runs into the risk of growing into a [big ball of mud](http://en.wikipedia.org/wiki/Big_ball_of_mud). – Spoike Jan 04 '13 at 19:14
  • @Spoike: Clever. I missed that. Well said on both accounts then :) – Steven Evers Jan 04 '13 at 23:20
  • Yeah, a Singleton could grow like that. But so could any non-Singleton class. The question is - is there any reason to think that it would? – Kevin Oct 05 '14 at 18:49
  • 2
    Possible duplicate of [Singleton without any state](https://softwareengineering.stackexchange.com/questions/340517/singleton-without-any-state) – Caleth May 24 '17 at 12:15

6 Answers6

12
  > Are immutable/stateless singletons bad?
  • No if they do not depend on other external Systems.
    • Example: A Stringutility that escapes html inside a string.
    • Reason: In unittests there is no need to replace this with a mock/simulator.
  • Yes if your immutable/stateless singleton depend on other external Systems/Services and if you want to do unittesting (testing in Isolation)
    • Example: a Service that depends on an External Tax-Calculator-Webservice.
    • Reason: In order to do unittests with this Service (in isolation) you need to simulate/mock the external Systems/Services.

For more details see the-onion-architecture


  • Singleton-s can make unit-testing (in isolation) more difficuilt/impossible and
  • hidden dependecies/coupling can be sees as a problem as explained by @yBee

I donot see other reasons why not using Singletons.

k3b
  • 7,488
  • 1
  • 18
  • 31
  • You would still have to mock that external web service if you want to test your class, even if it is not a (stateless) singleton. – Random42 Jan 05 '13 at 12:20
  • @m3th0dman i agree – k3b May 24 '17 at 10:25
  • _Or_ you could make a proper object, named `SafeString` (or `HtmlEscapedString`), that way you can not only can guarantee _at the compiler_ that strings will be safe to output, it will also be part of the design language. Your expression of the problem will be more complete, your communication with the reader of the code will be more effective and your code ultimately safer and more maintainable. – Robert Bräutigam Oct 17 '22 at 08:18
10

It always depends on the usage. I think the revolution comes from the fact, that every programmer learns this pattern as the object oriented pattern. Most forget to think about where it makes sense and where it doesn't.
This, of course, is true for every pattern. Just by using patterns you don't create good code or good software.

If you have a stateless singleton, why not use a class offering only static methods (or use a static class)?

Here some post regarding global variables and singletons in general.

I wouldn't be as strict as the author but he shows that for most cases where you think you need a singleton, you don't really need it.

StampedeXV
  • 201
  • 1
  • 6
  • 1
    Why not use a class with static methods? Inheritance for example... – Random42 Jan 04 '13 at 11:07
  • 3
    @m3th0dman: Doesn't sound like a good place for inheritance. – Billy ONeal Jan 04 '13 at 15:10
  • @BillyONeal You can say that something is good or bad for inheritance if you know the domain model, what is to be modeled in that way... – Random42 Jan 05 '13 at 12:18
  • 2
    @m3th0dman: Erm, no. I can be pretty positive without knowing anything about the domain model. Inheritance is for polymorphic behavior. But as a singleton, you aren't going to have polymorphic behavior. – Billy ONeal Jan 06 '13 at 01:49
  • @BillyONeal Why not? What forbids me from making my subclasses singletons? Think about EJB 3.1 and `@Singleton` annotation on an EJB class which is obliged to inherit from an interface which represents the business logic. – Random42 Jan 06 '13 at 11:36
  • 1
    @m3th0dman: Because to get the singleton object requires specifying the name of the singleton at the call site. Which means that you aren't using polymorphic behavior. Which means that composition is far more flexible than inheritance. – Billy ONeal Jan 06 '13 at 19:29
  • @BillyONeal Not necessarily; you can provide a factory over them, factory which always gives the same references. – Random42 Jan 07 '13 at 06:57
  • @m3th0dman: Then the class in question shouldn't be a singleton. The factory should maintain its own reference. – Billy ONeal Jan 07 '13 at 19:14
  • @BillyONeal The factory maintains it's own reference, and the object can be accessed only via the factory. Basically it is still a singleton since it has only one instance and has a global point of access (even via the factory). Why do you say it shouldn't be a singleton? If it is stateless, why should you need an instance each time is needed? – Random42 Jan 07 '13 at 22:17
  • @m3th0dman: Yes, I'm saying it shouldn't be a singleton. Making anything a singleton is an extremely limiting decision in a design -- you should have as few of them as possible. They are no better than global variables. You would be better off having the factory just having a `static` member variable containing the item in question. There's no need to encode that constraint into the design of the other objects. – Billy ONeal Jan 07 '13 at 22:27
  • @Billy ONeal I would agree with you for a typical singleton, but I do not see problems with a stateless singleton; that's why I asked this question. If the object is stateless, then different clients of this object can share that object; why shouldn't they? I don't see anything wrong with a stateless global value (if it is stateless, technically it is not a variable, since it cannot vary, being... stateless). – Random42 Jan 08 '13 at 06:49
  • To provide an example. In .Net many methods take a object for doing comparisons (ex. IComparable). In many cases the implementation will be stateless, but you cannot use a static class since you need an actual object. But you would only ever need one object, so a singleton would be perfectly appropriate. – JonasH Oct 17 '22 at 08:50
7

There is nothing an immutable stateless singleton can do that a static class can't.

There is simply no reason to add the extra level of complexity that ->Instance() creates, while plain call to a static method will be clearer, more conservative in terms of resources and probably faster.

It's not that they are wrong. It's that there is a better way to do it. There are scenarios where normal ("stateful") singletons are the right way to go. The evil with singleton is that they are often abused, with same bad results as global variables, but there are specific cases where using a singleton is simply correct. There are none such cases for the stateless ones.

SF.
  • 5,078
  • 2
  • 24
  • 36
  • I bet you can construct some cases where a Singleton has some advantages. Depending on scenario and Programming Language possibly (e.g. taking advantage of lazy loading). – StampedeXV Jan 04 '13 at 10:31
  • 3
    @StampedeXV: Yes, a stateful singleton certainly. A stateless and immutable one - I'd be really curious to hear any examples but I'm not holding my breath. – SF. Jan 04 '13 at 10:35
  • Ok, you have a point. I generalized your answer a little there. For immutable stateless I don't see any advantage either. – StampedeXV Jan 04 '13 at 10:39
  • 1
    With classes that only have static functions, you cannot use inheritance/polymorphism which is a big limit... – Random42 Jan 04 '13 at 11:08
  • Now it becomes fancy. Using Singleton but not knowing the exact type if you want to use inheritance? Still it is a valid use case - and who knows ... – StampedeXV Jan 04 '13 at 11:30
  • I really wonder what real-life scenario could require this kind of feature.] – SF. Jan 04 '13 at 11:44
  • @SF. I was writing some kind of a mini-framework for generating JPA Entities for some integration tests; in a simplified version an abstract base class has functionality for persisting/deleting and an abstract method which returns a generic type; the subclasses implement the method and actually return an entity. The subclasses can actually be singletons (hidden with a factory, they can be package-local) because there isn't any reason for many instances of the same class. – Random42 Jan 18 '13 at 23:05
  • @SF. You can take the address of an immutable stateless singleton... (C++) There I named one thing a static class cannot do that a stateless singleton can. You can put it in a hash. You can treat it like an object. You can do lots of things. Then again, many are probably useless. Then again, I don't care for singletons anyway. I would rather create one instance if I only need one instance. – Thomas Eding Aug 02 '13 at 18:51
  • Have a functor interface, with singleton implementations. Those singletons could be used polymorphically, far more useful than static methods. Though, to be fair, stateless functors would probably be pretty small (and thus you have little motivation to make them singleton, other than you can). – Kevin Oct 05 '14 at 18:52
  • 3
    _There is nothing an immutable stateless singleton can do that a static class can't._ well, static methods cannot implement an interface, which a singleton could – Michal M Oct 08 '15 at 10:35
4

The main problem with singleton is that it hides dependecies and coupling expecially when used in cross-cutting concerns scenario. See Singletons are Pathological Liars or Why Singletons are Evil for further reading.

From the other side, a state less singleton, if not abused, may be helpful and improve performance. Consider an example:

interface Interface
{
    void Method();
}

class StatelessSingleton : Interface
{
    public static readonly StatelessSingleton Instance = new StatelessSingleton();
    private StatelessSingleton() { }

    public void Method() { }
}

class User
{
    public User(Interface i) { /* ... */ }
}

Here, the StatelessSingleton acts as default implementation of the Interface and is put into the User constructor. There is no hard-coded coupling and hiden dependencies. We are unable to use a static class due to the underlying interface but there is no reason to create more than one instance of a default. That's why a stateless singleton seems to be an appropriate choice.

However, maybe we should use another pattern for a default implementation:

class Implementation : Interface
{
    private readonly Action _method;

    public Implementation()
    {
        _method = new Action(() => { /* default */ });
    }

    public Implementation(Action custom)
    {
        _method = custom;
    }

    public void Method()
    {
        _method();
    }
}

It hits the performance with respect to StatelessSingleton but constitutes a generic implementation of the Interface. Similar solution is used by IProgress interface.

Altough again, why allow to create more than one implementation of default behaviour? Yet we can combine the two:

class Implementation : Interface
{
    public readonly Implementation Default = new Implementation();

    private readonly Action _method;

    private Implementation()
    {
        _method = new Action(() => { /* default */ });
    }

    public Implementation(Action custom)
    {
        _method = custom;
    }

    public void Method()
    {
        _method();
    }
}

In conclusion, I believe that there are places (as depicted defaults) where Singletons are useful. The main definition of Singleton states that it disallow to create more than one instance of a class. It's as nuclear power. Can produce an energy or a bomb. It depends on human.

Glorfindel
  • 3,137
  • 6
  • 25
  • 33
yBee
  • 551
  • 4
  • 11
0

Some time ago I changed my definition. You shouldn't care about "singleton classes" but "singleton objects", defined as an object that has one specific purpose, that can be accessed from anywhere in your code base, and that exists or is created when it is needed and stays in existence forever. I don't care about the class. I don't care if the class has multiple instances, I just care that there is one specific instance that I use.

Some code of mine might have a variable where it stores this singleton object when created, or the singleton object may be passed in at creation time, that doesn't make a difference.

And since there is only one, it is obvious that any change of state affects everything. That's something you need to be aware of. It is neither good nor bad. It may be what you want. If not, you will need to use locking. For example, a translator object with properties "source language" and "destination language" will cause problems.

gnasher729
  • 42,090
  • 4
  • 59
  • 119
  • The key aspect of a singleton in the traditional sense, is that it is _static_ and it is not passed in to another object. It is specifically these characteristics that people criticize. So if you take those out of your definition, I don't think you're talking about the thing most people do. I suspect people do not have a problem with a `DatabaseConnection` for which only one instance exist. The problem is if that instance is static and also referred to directly by others. Or did I misunderstand you? – Robert Bräutigam Oct 17 '22 at 09:08
0

When you have a singleton that is completely stateless, then what you actually have is an utility class that's nothing but a collection of idempotent functions. One of those typical "toolbox" classes that contain a bunch of utility methods used by other classes.

So why not make it a class with only static methods? That saves you all the overhead of managing the singleton instance.

Philipp
  • 23,166
  • 6
  • 61
  • 67