Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If Singletons are so bad, why does Scala have language support for them? [duplicate]

Possible Duplicate:
Why are singleton objects more object orientated?

Why does Scala have language support for the Singleton anti-pattern? If Scala had inherited the static keyword from Java, what legitimate use cases of the object keyword would be left?

like image 329
fredoverflow Avatar asked Aug 01 '12 08:08

fredoverflow


1 Answers

There is an up-front difference at least, in that an object in Scala actually is an object (i.e. an instance), rather than in Java where it's just methods called on the class itself.

This means that it avoids one of the major complaints about singletons - since it is an instance, it can be passed around and wired into methods, and so can be swapped out for other implementations during tests, etc. If anything it's syntactic sugar for the recommended alternative to singletons - having a class with a getInstance() method returning the default, single instance.

That said, I consider that the Singleton anti-pattern is more about design than it is language features. If you structure your code base such that some monolithic dependency is implicitly wired throughout most of the classes, then you're going to have issues changing it - regardless of the language features.

There are legitimate use cases for objects in Scala (e.g. using case objects for messages to Actors, or having several of them extend a sealed trait as an alternative to enums). The language feature can be abused, but to my mind it's less abusable than Java's static, and more useful.

like image 98
Andrzej Doyle Avatar answered Nov 10 '22 00:11

Andrzej Doyle