DZone
Java Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Java Zone > What's So Evil About Singletons?

What's So Evil About Singletons?

Singletons might seem like a handy design pattern, but beware the hidden costs that tend to tag along during their implementation.

Devendra Tiwari user avatar by
Devendra Tiwari
·
Aug. 03, 17 · Java Zone · Opinion
Like (27)
Save
Tweet
22.59K Views

Join the DZone community and get the full member experience.

Join For Free

We've all come across this word ‘singleton,’ and most of us even know the definition of it. As Wikipedia says, “Singletons are classes which have a restriction to have only one instance.”

Maybe a few of were lucky enough to use it, but believe me, even if you have used it, you might not know how evil it is.

Single by choice

But first of all, let me get everyone on the same page.

So to be more clear, “This pattern involves a single class which is responsible for creating an object while making sure that only one object gets created.”

Note: Most of the code is in Java, but it is so simple that anybody can understand it.
class Singleton {
    private static Singleton INSTANCE = null;
    private String criticalData;
    private Singleton() {
        criticalData = "This should be unique and state should be universal";
    }
    synchronized static Singleton getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new Singleton();
        }
        return INSTANCE;
    }

    public String getString() {
        return this.criticalData;
    }

    public void setCriticalData(String value) {
        criticalData = value;
    }
}


By now, we know what a singleton class is and how it works. So where is the defect? Hint: The most obvious problem is hidden in line 7.

Since a synchronized block can be accessed one thread at a time, this might create a bottleneck for even getting the instance of the object.

But there are other, lesser-known problems.

Singletons and State

Singletons are enemies of unit testing. One of the major requirements of unit testing is that each test should be independent of others. This can cause tests to pass when, really, it's because they were called in a particular order

One Object Created

Isn’t it a complete violation of the Single Responsibility Principle, which states, “A class should have one, and only one, reason to change.” Basically, a class should not know whether it is a singleton or not. So if you want to limit the ability to instantiate, use the factory or builder patterns, which encapsulates creation. There, you can limit the number of objects to one or whatever you wish for.

‘Singleton’ is a fancy word for ‘global variable.’

Singletons Provide Global State

Exactly, that's why we have singletons. Yes. But at what cost? (Global variables were bad! Remember?) This provides a gateway to some service in your application so that we don’t have to pass around a reference to the service. The urge to create something global to avoid passing it around is a smell in your design.

unit test Object (computer science) Pass (software) application Factory (object-oriented programming) Blocks Clear (Unix)

Published at DZone with permission of Devendra Tiwari. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How to Submit a Post to DZone
  • Why Blockchain Technology Is the Future of Data Storage
  • TURN Time Into Value
  • Automatically Creating Microservices Architecture Diagrams

Comments

Java Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo