DZone
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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Languages
  4. 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 · Opinion
Like (27)
Save
Tweet
Share
22.84K 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

  • A Brief Overview of the Spring Cloud Framework
  • How Observability Is Redefining Developer Roles
  • Upgrade Guide To Spring Data Elasticsearch 5.0
  • How To Create and Edit Excel XLSX Documents in Java

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • 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: