Words of Wisdom:

"Reguardless of his looks, he isn't such a bad guy." - BIGWAVE01

Why Singletons Are Controversial

  • Date Submitted: 07/16/2013 05:48 AM
  • Flesch-Kincaid Score: 49.8 
  • Words: 582
  • Essay Grade: no grades
  • Report this Essay
Why Singletons Are Controversial¶The use of singletons is actually a fairly controversial subject in the Java community; what was once an often-used design pattern is now being looked at as a less than desirable coding practice. The problem with singletons is that they introduce global state into a program, allowing anyone to access them at anytime (ignoring scope). Even worse, singletons are one of the most overused design patterns today, meaning that many people introduce this possibly detrimental global state in instances where it isn't even necessary. What's wrong with singletons' use of global state?
First, programs using global state are very difficult to test. One of the hallmarks of testability is a loose coupling of classes, allowing you to isolate a single class and test it completely. When one class uses a singleton (and I'm talking about a classic singleton, one that enforces it own singularity thorough a static getInstance() method), the singleton user and the singleton become inextricably coupled together. It is no longer possible to test the user without also testing the singleton. In many cases, this is a deal breaker that can prevent a developer from testing a class at all, especially if the singleton represents a resource that should not be updated by tests (i.e. an important database). The ideal solution here is to pass in the singleton as a parameter in the user's constructor, allowing a tester to easily mock out the singleton for tests. The singleton then doesn't have to enforce its own singularity; this can be handled by the client or a factory class, which could produce the real version or a test version, eliminating the global state altogether. In fact, it should be considered a violation of the Single Responsibility Principle of OO design to have an object responsible for its own singularity as well as its normal tasks.
Second, programs that rely on global state hide their dependencies. One of the unique abilities of a singleton is that...


Express your owns thoughts and ideas on this essay by writing a grade and/or critique.

  1. No comments