Singleton Pattern

A

Adi

Dear all,

I have a question about singleton pattern. In my java user group,
someone said that this pattern should be avoided, but he didn't explain
the reason.

So I am curious here, is this statement true ?

Someone else replied that this pattern is hard to test and make other
classes tightly coupled with this Singleton class. Somehow I doubt it
but I also can find any argument for that. What I know is just because
this pattern is hard to test doesn't mean that this pattern should be
avoided right ? I use this pattern a lot of times and found it useful.

Do you have any comments ?

Thanks,
 
S

saotome

I personally use it plenty of times. I don't share your college's
opinion. I don't understand why it would create tight coupling vs. a
regular instantiation of an object.
 
R

rxreyn3

It's a matter of personal preference usually. The decision I make is
on whether or not I can make static methods calls first. If I can't
make static method to accompilsh what a class needs to do, yet I need
to maintain a unique set of information, i'll create a singleton class.

Ryan
 
K

Karl Uppiano

Adi said:
Dear all,

I have a question about singleton pattern. In my java user group,
someone said that this pattern should be avoided, but he didn't explain
the reason.

So I am curious here, is this statement true ?

Sometimes, I suppose.
Someone else replied that this pattern is hard to test and make other
classes tightly coupled with this Singleton class. Somehow I doubt it
but I also can find any argument for that. What I know is just because
this pattern is hard to test doesn't mean that this pattern should be
avoided right ? I use this pattern a lot of times and found it useful.

Do you have any comments ?

If your design needs a singleton, then you should use a singleton. Perhaps
your colleague was referring to some of the potential pitfalls (everything
has pitfalls) described here:
http://www.javaworld.com/javaworld/jw-04-2003/jw-0425-designpatterns.html
 
M

Mark Jeffcoat

Adi said:
Dear all,

I have a question about singleton pattern. In my java user group,
someone said that this pattern should be avoided, but he didn't explain
the reason.

There are a couple of really good reasons to avoid singletons:

First, because Singletons are Global Variables, returned from
the grave where we tried to bury them so many years ago. They're
very often used to pull in bits of extra state deep inside a
program, jumping out without warning or any sort of control.

(Most common form: If your singleton has a name like "Configuration",
you've got a cluster of global variables in a pretty wrapper.)



Second, because singletons are hard to test. To write useful
unit tests, you have to know that the behavior of the code
under test is the same as the behavior of the code in its
final environment. Singletons allow you to not only make
arbitrary changes in the environment, but they also introduce
an order dependence into your tests. Every test that runs
can change the state of your singleton, and that new state
is carried over to the next test. Since this order probably
is completely unrelated to the order in which the bits you're
testing would be used in production, your tests are going to be
much less likely to catch real problems--really, it's nearly
impossible to guarantee that the behavior of code under test
is not arbitrarily different than the same code in the
production environment.


Third, using a singleton denies the possibility of certain
extensions to your software. Someday, you're going to want
two instances of whatever you were doing originally, and then
many, and it's going to be annoying to have to run each
instance in a separate JVM. This has actually happened to me,
and I was, in fact, annoyed.



Reason 1 is enough: Globals are bad, because they will make
your software hard to understand, and harder to maintain.
 
C

Chris Thomasson

Adi said:
Dear all,

I have a question about singleton pattern. In my java user group,
someone said that this pattern should be avoided, but he didn't explain
the reason.

So I am curious here, is this statement true ?

Someone else replied that this pattern is hard to test and make other
classes tightly coupled with this Singleton class. Somehow I doubt it
but I also can find any argument for that. What I know is just because
this pattern is hard to test doesn't mean that this pattern should be
avoided right ? I use this pattern a lot of times and found it useful.

Do you have any comments ?


http://appcore.home.comcast.net/vzdoc/atomic/static-init/

http://groups.google.com/group/comp.programming.threads/browse_frm/thread/c7d417e0b8aa516d
 
C

Chris Uppal

Mark said:
First, because Singletons are Global Variables, returned from
the grave where we tried to bury them so many years ago.

I often read this, but I don't think there's an ounce of truth in it.

More accurately, I think:

There is a need (a perfectly genuine need) to be able to put data in some
"well-known" place where things can get at it. And without the data (or its
location) needing to know about the users in advance (so the data is decoupled
from its users, even though the users are coupled to the data -- but that's
inevitable, it's part of the underlying logic, not an accident of poor design).

Global variables are one way of providing that. And when used for that purpose
they work well. Of course, they can be misused to create "spaggetti data".
But that doesn't mean that they are bad when used correctly.

One practical problem with global variables (considered as a technology
intended to meet the requirement described above), is the name-clash thing.
One solution to that is to use something like the Singleton pattern (or even
just a public static field) in Java. That addresses exactly the same
underlying need, but vastly reduces (not eliminates) the problem with unwanted
name clashes. As you say, Singletons are essentially the same as global
variable -- which is what you'd expect, they have been invented to address
exactly the same need.

After all, what is a DBMS if it is not a chunk of (mutable) data available to
all users at a well-known location ? Indeed it is available enterprise-wide,
which puts poxy little Singleton classes in the shade ;-) Are DBMS's without
problems ? Of course not, and some of those problems are exactly the same as
the ones exhibited by other global varaiables (or Singletons) -- concurrent
access, over-tight coupling, brittleness -- but I don't think many pundits
would advocate scrapping the DBMS for those reasons.

There's nothing wrong with global data...

-- chris
 
C

Chris Uppal

Adi said:
Someone else replied that [Singleton] is hard to test and make other
classes tightly coupled with this Singleton class. Somehow I doubt it
but I also can find any argument for that.

Singleton /can/ be a symptom of poor design. The worst thing about it (IMO) is
that people tend to focus on the idea that you /must/ only have one instance.
There is nothing wrong with /actually/ having only one instance, plus a
well-known way to find it; but for some weird reason people often go beyond
that and make it impossible to create other instances. That is restrictive,
unnecessary, and brittle.

Give you an example. Say we have some printer settings, and we'd like them to
be globally available. That's all fine so far -- a perfectly reasonable thing
to want to do. So we set up a class, PrinterSettings, and arrange that there
shall be a well-known instance (probably populated from the user's personal
preferences). We'll make that Singleton instance available from a static
method, PrinterSettings.getDefault(). That's still fine and dandy, and is
exactly the kind of thing that Singleton pattern is good for. But now, some
idiot decides to make it impossible to create /other/ instances of our
Singleton's class, that has all sorts of bad effects:

1) We probably can't risk modifying the Singleton instance, because it
might be in use by more than one thread. That was a problem with our original
design too, of course, and so we may (depending on the application) need a way
to avoid that problem. In our original design, the solution was simple -- just
make a copy of the PrinterSettings.getDefault() whenever we need a stable set
of settings. But with this new restriction we can't do that, so we have to
design some sort of complicated (and probably brittle) locking protocol to
allow us to "freeze" the settings while we are actually using them.

2) Nothing, /nothing/, has actually been gained by the restriction. The
software is not more flexible, more reliable, nor easier to understand. Its
just a bit of programmer fascism -- "Anything not mandatory is forbidden!".
Probably driven by insecurity.

3) Since we now have this single Singleton, programmers will be tempted to
write the code on the assumption that /everything/ will use that instance --
why pass it in a parameter when the called code can find the PrinterSettings
object directly by itself ? That leads to brittleness. If (or more likely,
when) the requirements change, e.g. to have two printers in the system, you
have to track down and eliminate all the code which /should/ have been
parameterised on the PrinterSettings to use, but which have hard-wired the
one-and-only-one Singleton assumption instead.

There may be situations where a one-and-only-one rule /is/ necessary -- but
they are very rare[*], and crop up far less often than legitimate needs for a
properly-written Singleton.

As to the "increased coupling" assertion. That's not really a problem of
Singleton as such, but of its typical expression using static methods -- all
static methods (and fields) lead to increased coupling (and so does direct us
of constructors, but that's another story...)

-- chris

[*] I can't think of any off the top of my head.
 
?

=?ISO-8859-1?Q?Arne_Vajh=F8j?=

Adi said:
I have a question about singleton pattern. In my java user group,
someone said that this pattern should be avoided, but he didn't explain
the reason.

So I am curious here, is this statement true ?

Someone else replied that this pattern is hard to test and make other
classes tightly coupled with this Singleton class. Somehow I doubt it
but I also can find any argument for that. What I know is just because
this pattern is hard to test doesn't mean that this pattern should be
avoided right ? I use this pattern a lot of times and found it useful.

Do you have any comments ?

Singleton is a valid pattern.

Most of the criticism found on the net is ridiculous ("if you implement
it wrong then it will not work" type).

The only real problem I can think of is a modifiable singleton in a
clustered environment (or other multi JVM environment).

Arne
 
R

rxreyn3

I'll be the first to admit that I have learned alot in this short
discussion. Even if I don't agree.

Ryan
 
A

andrewmcdonagh

Dear all,

I have a question about singleton pattern. In my java user group,
someone said that this pattern should be avoided, but he didn't explain
the reason.

So I am curious here, is this statement true ?

Someone else replied that this pattern is hard to test and make other
classes tightly coupled with this Singleton class. Somehow I doubt it
but I also can find any argument for that. What I know is just because
this pattern is hard to test doesn't mean that this pattern should be
avoided right ? I use this pattern a lot of times and found it useful.

Do you have any comments ?

Thanks,


This has been discussed to death during the last 10 years......

Take a look at
http://groups-beta.google.com/group...t&q=Singleton+Pattern&rnum=5#0539f2454634cfca

for such a discussion.

Andrew
 
A

andrewmcdonagh

Most of the criticism found on the net is ridiculous ("if you implement
it wrong then it will not work" type).

The only real problem I can think of is a modifiable singleton in a
clustered environment (or other multi JVM environment).

Arne

The Singleton is a valid pattern.

The Singleton is the most used pattern.

The Singleton is the most abused pattern (e.g. used mainly for finding
something at a well know location, rather than to enforce 'just one
instance')

See:
http://groups-beta.google.com/group...t&q=Singleton+Pattern&rnum=5#0539f2454634cfca


The majority of times, having a global access to something is the
usual reason for creating a Singleton. In these cases, its not a
singleton that was required, but a singleton containing mutliple items
- in other works a 'Container' or 'Toolbox'
 
D

Daniel Pitts

Adi said:
Dear all,

I have a question about singleton pattern. In my java user group,
someone said that this pattern should be avoided, but he didn't explain
the reason.

So I am curious here, is this statement true ?

Someone else replied that this pattern is hard to test and make other
classes tightly coupled with this Singleton class. Somehow I doubt it
but I also can find any argument for that. What I know is just because
this pattern is hard to test doesn't mean that this pattern should be
avoided right ? I use this pattern a lot of times and found it useful.

Do you have any comments ?

Thanks,

The main reason is that it hinders Unit testing, but there are many
other good arguments against singletons as well.

The alternative is often the use of Dependency Injection. This allows
you to decouple the process of obtaining an object from the class
altogether. A class which uses a Singleton will have to know exactly
where to get it, and therefor coupling it to the Singleton. A class
which utilizes Dependency Injection will know that it wants the
"Singleton" object, but instead of asking for it directly, it will be
given it by some outside source.

Lets give an analogy in psuedo-Java:

class Plant {
double lightObsorbed = 0;
void obsorbLight() {
listObsorbed +=
LightSourceSingletonFactory.getLightSource().getLightInWatts();
}
}

the Plant class is now coupled to LightSourceSingletonFactory and the
LightSource interface. While it is not coupled to the implementation
of LightSource.

class Plant {
LightSource lightSource;
void obsorbLight() {
listObsorbed += lightSource.getLightInWatts();
}

void setLightSource(LightSource lightSource) {
this.lightSource = lightSource;
}
}

Now, plant is no longer coupled to a singleton factory at all, and only
the interface of LightSource. This would be useful of some day, your
business logic needed to have both indoor plants (class LightBulb
implements LightSource), and outdoor plants (class Sun implements
LightSource).

It also allows you to have a unit test with a "mock" LightSource
object.


Dependency Injection is a subcategory of Inversion of Control. The
basis of the spring framework.

While the Singleton pattern DOES have uses, there are often other ways
to achieve the same goal which lend themselves to a more flexible
architecture. If you only need to ensure that there is only one
instance of a particular class (eg. for a resource heavy object), you
can still use DI and IoC, especially since the classes themselves don't
do any form of object instansiation or retrieval.

It removes the burdon of object instantiation or retrieval from the
business domain, and puts it into the framework.

Hope this helps,
Daniel.
 
?

=?ISO-8859-1?Q?Arne_Vajh=F8j?=

The Singleton is a valid pattern.

The Singleton is the most used pattern.

The Singleton is the most abused pattern (e.g. used mainly for finding
something at a well know location, rather than to enforce 'just one
instance')

See:
http://groups-beta.google.com/group...t&q=Singleton+Pattern&rnum=5#0539f2454634cfca

The majority of times, having a global access to something is the
usual reason for creating a Singleton. In these cases, its not a
singleton that was required, but a singleton containing mutliple items
- in other works a 'Container' or 'Toolbox'

As with most patterns there are a cases where it can be debated whether
a specific pattern is the best solution or not.

Singleton is probably the most widely abused. But no surprise if it
is the most widely used.

But from a practical point of view, then I would say that even
in the cases where singleton is not the best solution, then it
is usually not a bad solution either.

There are many much worse diseases than being over enthusiastic
about singletons.

Arne
 
K

Karl Uppiano

As with most patterns there are a cases where it can be debated whether
a specific pattern is the best solution or not.

Singleton is probably the most widely abused. But no surprise if it
is the most widely used.

But from a practical point of view, then I would say that even
in the cases where singleton is not the best solution, then it
is usually not a bad solution either.

There are many much worse diseases than being over enthusiastic
about singletons.

I tend to agree. The question should not be "is the design pattern good or
bad?" but rather, "does the solution require this design pattern?". A good
design should attempt to choose a "good one" from the entire catalog of
design patterns. All engineering is a trade-off, so there probably isn't a
"best one", only one that doesn't suck too badly in any likely use-case.
 
N

Nirav

Adi said:
Dear all,

I have a question about singleton pattern. In my java user group,
someone said that this pattern should be avoided, but he didn't explain
the reason.

So I am curious here, is this statement true ?

Someone else replied that this pattern is hard to test and make other
classes tightly coupled with this Singleton class. Somehow I doubt it
but I also can find any argument for that. What I know is just because
this pattern is hard to test doesn't mean that this pattern should be
avoided right ? I use this pattern a lot of times and found it useful.

Do you have any comments ?

Thanks,

I've few views of mine apart from the useful discussion here.
Personally, I find singletons handy in most programming environments.
My take on singleton is: never use them unless its inevitable (e.g.
config registries and stateless utilities). Singleton implementations
can easily become difficult to unit test, mock; which results in severe
problems in large applications (and i hate spending time on instance
recreation hacks, yuk). Most of the time I endup implementing minor
testable variant of it, called monostate.

- Nirav Thaker
 
C

Chris Uppal

Karl said:
I tend to agree. The question should not be "is the design pattern good or
bad?" but rather, "does the solution require this design pattern?". A good
design should attempt to choose a "good one" from the entire catalog of
design patterns.

You may not have meant that exactly how it sounded, but if you do then I
disagree profoundly. A good design is created on its own merits, /not/ by
scanning some menu of available patterns.

-- chris
 
?

=?ISO-8859-1?Q?Arne_Vajh=F8j?=

Chris said:
You may not have meant that exactly how it sounded, but if you do then I
disagree profoundly. A good design is created on its own merits, /not/ by
scanning some menu of available patterns.

The difference between:

A) Create a good design based on your experience and knowledge including
knowledge about established patterns.

B) At some point in the design process make a quick check on whether
the problem matches an established pattern for design.

is not that big.

It is rather common to assume that if two solutions are technical
equally good, then it is best to choose the most well known
solution, because that makes the code more readable/maintainable.

Arne
 
K

Karl Uppiano

Chris Uppal said:
You may not have meant that exactly how it sounded, but if you do then I
disagree profoundly. A good design is created on its own merits, /not/ by
scanning some menu of available patterns.

A good design is created on its own merits, but IME, a large application is
usually built up from a judicious selection of standard components and
design patterns: For loops, while loops, try/catch blocks, if/else blocks,
switch statements, goto's, functional decomposition, object orientation,
threads, critical sections, mutexes, semaphores, stacks, queues, arrays,
lists, vectors, hash maps, singletons, resource adapters, enterprise service
busses, and so on, every one a design pattern of some sort.

The actual design is application-specific of course, and its quality depends
on the knowledge, ingenuity and creativity of the designer. However, in a
modular, object-oriented world, re-use is encouraged. Therefore, I usually
*do* scan some menu, in my mind, of available modules and design patterns,
not always consciously of course -- starting with the JDK API or C++ object
libraries, Google, -- looking for parts, to see if someone already invented
what I need. That's the "research" part of R&D. In many cases, I will extend
or modify what's available. If nothing is available, then I will create my
own module from scratch as a last resort. Of course, the
application-specific "glue" logic is usually not available off-the-shelf.

My particular coding style comes from the electronics industry, where I
started my career. In electronics, everything is modular: Resistors,
capacitors, inductors, transistors, integrated circuits... Sure, you could
make your own components from scratch, but unless you're in that line of
work, it is extremely time-consuming and fraught with difficulty. So,
vendors build solutions from a menu of available parts and design patterns -
e.g., most transistor audio amplifiers are based on the same tried and true
design pattern, modified to meet specific requirements. But from these
standard components and design patterns, I can build a cell phone, a
wireless router, a television, microwave oven...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Singleton Pattern 7
Singleton vs static 11
The Towers of Hanoi 3
Processing in Python help 0
Help with Singleton SafeConfigParser 4
Singleton Pattern or Rubbish? 2
Pattern suggestion 10
Singleton thread 1

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,239
Members
46,827
Latest member
DMUK_Beginner

Latest Threads

Top