Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

What's So Evil About Singletons?

DZone's Guide to

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.

· Java Zone
Free Resource

Never build auth again! The Okta Developer Platform makes it simple to implement authentication, authorization, MFA and more in Java applications. Get started with the free API.

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.

Build and launch faster with Okta’s user management API. Register today for the free forever developer edition!

Topics:
java ,design pattens ,singleton ,java performance ,singleton design pattern ,singleton pattern

Published at DZone with permission of Dave Ranjan. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}