Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton Design Pattern: Pitfalls [closed]

Tags:

Not sure of downfalls using strict global state implementation. When is singleton not ideal for an application?

like image 539
Sajal Dutta Avatar asked Sep 19 '09 11:09

Sajal Dutta


People also ask

What is a common pitfall when using the singleton pattern?

One of the main disadvantages of singletons is that they make unit testing very hard. They introduce global state to the application. The problem is that you cannot completely isolate classes dependent on singletons. When you are trying to test such a class, you inevitably test the Singleton as well.

Why should singletons be sealed?

Marking the class sealed prevents someone from trivially working around your carefully-constructed singleton class because it keeps someone from inheriting from the class.

What are the consequences of singleton design pattern?

Some consequences of the Singleton pattern include controlling access, permitting subclassing, and enhancing flexibility.

What is one of the most common mistakes you can make when implementing a singleton?

A common mistake with that implementation is to neglect synchronization, which can lead to multiple instances of the singleton class.


1 Answers

Singleton is generally a bad idea if you are doing unit testing, and its generally a bad idea not to do unit testing (or BDD or Acceptance Testing).

Making objects have global state means that the unit tests you write involving these objects will be isolated and disjoint from one another. Instead, you will have to worry about resetting the state for each test and believe me ... that is never done 100% of the time. If you don't reset the global state then you start to get very weird and hard to debug errors in your tests that waste time.

Global state also increases coupling in your code and makes it very hard to refactor.

The ideal method would be to use an IoC/DI container (Spring, Guice, etc.) to request objects. These containers often have ways of making objects appear as 'Singletons' but they also have ways of modifying that behavior depending on the situation (i.e. unit testing vs. your domain code).

This all depends on the size of your problem of course. If you're hacking together a 4-class test rig to try something out then go ahead and use a Singleton. However, as soon as that project takes on life and grows bigger and more complex then refactor the Singleton out.

like image 62
Jeffrey Cameron Avatar answered Oct 17 '22 03:10

Jeffrey Cameron