By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
428,558 Members | 1,533 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 428,558 IT Pros & Developers. It's quick & easy.

Creating framework for singleton pattern?

P: n/a
I wish to build a framework for our developers that will include a singleton
pattern.
But it can not be a base class because it has a private constructor and
therefore can be inherit.
I thought maybe a Template can be use for that, but C# does not support
Templates (will be C# generics in mid 2005).
Does anyone have a solution on how the singleton pattern can be written, in
C#, as a framework/ infrastructure class, so users can use this class and
extend it to their desire?

--
Regards
Sharon G.
Nov 16 '05 #1
Share this Question
Share on Google+
21 Replies


P: n/a
Sharon <Sh****@discussions.microsoft.com> wrote:
I wish to build a framework for our developers that will include a singleton
pattern.
But it can not be a base class because it has a private constructor and
therefore can be inherit.
I thought maybe a Template can be use for that, but C# does not support
Templates (will be C# generics in mid 2005).
Generics aren't the same as templates anyway - I can't see how they'd
help here.
Does anyone have a solution on how the singleton pattern can be written, in
C#, as a framework/ infrastructure class, so users can use this class and
extend it to their desire?


You basically can't. However, the singleton pattern can be correctly
implemented so simply, I think it's not too much hassle to do it in
each place you need a singleton. At its barest, it's just:

public class Singleton
{
public static readonly Singleton Instance = new Singleton();

Singleton()
{
}
}

If you want to guarantee laziness, you could be the initialization of
Instance into a static constructor, but most of the time you won't
really need that.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #2

P: n/a
Sharon wrote:
I wish to build a framework for our developers that will include a singleton
pattern.
But it can not be a base class because it has a private constructor and
therefore can be inherit.
I thought maybe a Template can be use for that, but C# does not support
Templates (will be C# generics in mid 2005).
Does anyone have a solution on how the singleton pattern can be written, in
C#, as a framework/ infrastructure class, so users can use this class and
extend it to their desire?


Concrete patterns are not (always) suitable to be part of a framework's
class hierarchy. Patterns are, well, design patterns. They may
consist of a bunch of classes, etc.

An inheritable singleton can be done, but it's quite ugly:

public class A {
public static A Instance = new A();
protected A() {}
}

public class B : A {
public static new B Instance = new B();
protected B() : base() {}
}

It's not worthwhile.

bye
Rob
Nov 16 '05 #3

P: n/a
Wouldn't that be the same thing Jon, as the C# compiler simply puts static field initializers at the start of a generated (if one doesn't already exist) static constructor

Regards

Richard Blewett - DevelopMentor
http://staff.develop.com/richardb/weblog
If you want to guarantee laziness, you could be the initialization of
Instance into a static constructor, but most of the time you won't
really need that.

Nov 16 '05 #4

P: n/a
If you find a way to put a singleton into a framework pattern, please keep
it to yourself.
Do not share it.

Singletons are good, but only to a point, and they are very easy to misuse.
Please see:
http://c2.com/cgi/wiki?SingletonGlobalProblems

I encourage singletons primarily as a transition from global variables to
more useful OO patterns. I do use singletons, but I keep in mind their
limitations and the cautions before I do. More than once, I've refactored
AWAY from a singleton.

They are far from a panacea and, in the wrong hands, are far worse for good
OO programming than "Edit and Continue" (a topic that sparked a good bit of
conversation in the past few days).

Good luck,
--- Nick

"Sharon" <Sh****@discussions.microsoft.com> wrote in message
news:40**********************************@microsof t.com...
I wish to build a framework for our developers that will include a singleton pattern.
But it can not be a base class because it has a private constructor and
therefore can be inherit.
I thought maybe a Template can be use for that, but C# does not support
Templates (will be C# generics in mid 2005).
Does anyone have a solution on how the singleton pattern can be written, in C#, as a framework/ infrastructure class, so users can use this class and
extend it to their desire?

--
Regards
Sharon G.

Nov 16 '05 #5

P: n/a
Richard Blewett [DevelopMentor] <ri******@develop.com> wrote:
Wouldn't that be the same thing Jon, as the C# compiler simply puts
static field initializers at the start of a generated (if one doesn't
already exist) static constructor


No, although I didn't realise it until I was investigating a question
for someone. The difference is in terms of beforefieldinit.

See http://www.pobox.com/~skeet/csharp/beforefieldinit.html for
details.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #6

P: n/a
Nick Malik <ni*******@hotmail.nospam.com> wrote:
If you find a way to put a singleton into a framework pattern, please keep
it to yourself.
Do not share it.

Singletons are good, but only to a point, and they are very easy to misuse.
Please see:
http://c2.com/cgi/wiki?SingletonGlobalProblems


True. It might be worth mentioning that in my singleton page, before
going onto the implementations... Hmm.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #7

P: n/a
ah yes, beforefieldinit, forgot sbout that - although in the code you showed it would make no difference as you had no static methods that touched no data so the effect would be the same in this case.

Regards

Richard Blewett - DevelopMentor
http://staff.develop.com/richardb/weblog
No, although I didn't realise it until I was investigating a question
for someone. The difference is in terms of beforefieldinit.

See http://www.pobox.com/~skeet/csharp/beforefieldinit.html for
details.

Nov 16 '05 #8

P: n/a

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Nick Malik <ni*******@hotmail.nospam.com> wrote:
If you find a way to put a singleton into a framework pattern, please
keep
it to yourself.
Do not share it.

Singletons are good, but only to a point, and they are very easy to
misuse.
Please see:
http://c2.com/cgi/wiki?SingletonGlobalProblems


True. It might be worth mentioning that in my singleton page, before
going onto the implementations... Hmm.


It might be, but I would urge you to be careful. Writing a mention that
doesn't require a considerable amount of research on the part of the
reader(many of the people reading the articles will be beginners, after all)
may take a fair amount of thought. All of the discussion on the wiki still
doesn't seem to come even close to providing a real answer to anyone, its
still entirely personal extrapolation based on badly formed or incomplete
information. It would probably be a greater disservice to imbue confusion
within your page than it would be to make no mention at all.
Nov 16 '05 #9

P: n/a
Richard Blewett [DevelopMentor] <ri******@develop.com> wrote:
ah yes, beforefieldinit, forgot sbout that - although in the code you
showed it would make no difference as you had no static methods that
touched no data so the effect would be the same in this case.


Nope - because beforefieldinit allows the type to be initialised
earlier than it would otherwise. For instance:

using System;

class Test
{
static void Main()
{
Console.WriteLine ("A");
object x = Singleton.Instance;
Console.WriteLine ("B");
}
}

class Singleton
{
public static Singleton Instance = new Singleton();

static Singleton(){}

Singleton()
{
Console.WriteLine ("Singleton constructor");
}
}

As above, the output *must* be:

A
Singleton constructor
B

Commenting out the static constructor (which looks like it's not
changing anything) the output can be (and is, on my box):

Singleton constructor
A
B

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #10

P: n/a
Hmm its a mixed blessing beforefieldinit. Looking at the amended code below it would be better to delay initialization until the last possible moment (or not at all)? If you change your code to

using System;

class Test
{
static void Main()
{
Console.WriteLine ("A");
if( DateTime.How.Hour < 10 )
{
object x = Singleton.Instance;
}
Console.WriteLine ("B");
}
}

class Singleton
{
public static Singleton Instance = new Singleton();

static Singleton(){}

Singleton()
{
Console.WriteLine ("Singleton constructor");
}
}

and run it after 10:00am you get
A
B

with the cctor and
Singleton constructor
A
B

without it.

Regards

Richard Blewett - DevelopMentor
http://staff.develop.com/richardb/weblog
Richard Blewett [DevelopMentor] <ri******@develop.com> wrote:
ah yes, beforefieldinit, forgot sbout that - although in the code you
showed it would make no difference as you had no static methods that
touched no data so the effect would be the same in this case.


Nope - because beforefieldinit allows the type to be initialised
earlier than it would otherwise. For instance:
Nov 16 '05 #11

P: n/a
Richard Blewett [DevelopMentor] <ri******@develop.com> wrote:
Hmm its a mixed blessing beforefieldinit. Looking at the amended code
below it would be better to delay initialization until the last
possible moment (or not at all)?


Well, it *might* be better. Guaranteeing that the initialization is
"properly lazy" (i.e. using a static constructor) potentially avoids
creating something unnecessarily, but you pay a performance penalty
every time you need to use anything to do with the class. The penalty
is small, but if you're using it in a tight loop somewhere, it could
become significant compared with the penalty of possibly constructing
something which isn't needed.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #12

P: n/a
I respectfully disagree, Daniel.

The Wiki page that I linked is one of hundreds of pages that call into
question the usefulness, in the long run, of the Singleton pattern.

I believe in "informed consent". That is, if someone is going to encourage
me to engage in a risky behavior, they should have the integrity to share
the risks with me beforehand. While I don't think it is wise to turn a
valuable technical article into an opinion piece, the OO world has learned
that this pattern is being widely misused... (and others as well, including
Visitor, apparently). That learning should not be ignored just because it's
not "technical" in nature.

To the contrary, attached to every set of instructions for how to correctly
use household cleaner, there is a warning label about keeping it away from
children. We should be willing to put a warning label on patterns as
well... especially the ones that get more misuse than others.

--- Nick

"Daniel O'Connell [C# MVP]" <onyxkirx@--NOSPAM--comcast.net> wrote in
message news:Om**************@TK2MSFTNGP11.phx.gbl...

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Nick Malik <ni*******@hotmail.nospam.com> wrote:
If you find a way to put a singleton into a framework pattern, please
keep
it to yourself.
Do not share it.

Singletons are good, but only to a point, and they are very easy to
misuse.
Please see:
http://c2.com/cgi/wiki?SingletonGlobalProblems
True. It might be worth mentioning that in my singleton page, before
going onto the implementations... Hmm.


It might be, but I would urge you to be careful. Writing a mention that
doesn't require a considerable amount of research on the part of the
reader(many of the people reading the articles will be beginners, after

all) may take a fair amount of thought. All of the discussion on the wiki still
doesn't seem to come even close to providing a real answer to anyone, its
still entirely personal extrapolation based on badly formed or incomplete
information. It would probably be a greater disservice to imbue confusion
within your page than it would be to make no mention at all.

Nov 16 '05 #13

P: n/a
Indeed, thats why I said it was a *mixed* blessing rather than terrible :-)

Sheesh I've got to be more careful, every time I say that something is a mixed blessing or I have mixed feelings about something everyone assumes I hate the feature ;-)

Regards

Richard Blewett - DevelopMentor
http://staff.develop.com/richardb/weblog

Richard Blewett [DevelopMentor] <ri******@develop.com> wrote:
Hmm its a mixed blessing beforefieldinit. Looking at the amended code
below it would be better to delay initialization until the last
possible moment (or not at all)?


Well, it *might* be better. Guaranteeing that the initialization is
"properly lazy" (i.e. using a static constructor) potentially avoids
creating something unnecessarily, but you pay a performance penalty
every time you need to use anything to do with the class. The penalty
is small, but if you're using it in a tight loop somewhere, it could
become significant compared with the penalty of possibly constructing
something which isn't needed.

Nov 16 '05 #14

P: n/a
I discovered this when FxCop gave me a Crtical warning about "Do not
declare explicit static constructors". The explanation in the docs is
a bit fluffy so I did some ILDASM exploration.

I'm not sure it is such a critical issue in application code (in
framework and library code perhaps it is more of a concern). It would
be nice if beforefieldinit could be explicitly set or removed with a
class level attribute.

--
Scott
http://www.OdeToCode.com/blogs/scott/

On Wed, 20 Oct 2004 15:32:56 +0100, Jon Skeet [C# MVP]
<sk***@pobox.com> wrote:
Richard Blewett [DevelopMentor] <ri******@develop.com> wrote:
Hmm its a mixed blessing beforefieldinit. Looking at the amended code
below it would be better to delay initialization until the last
possible moment (or not at all)?


Well, it *might* be better. Guaranteeing that the initialization is
"properly lazy" (i.e. using a static constructor) potentially avoids
creating something unnecessarily, but you pay a performance penalty
every time you need to use anything to do with the class. The penalty
is small, but if you're using it in a tight loop somewhere, it could
become significant compared with the penalty of possibly constructing
something which isn't needed.


Nov 16 '05 #15

P: n/a
Scott Allen <bitmask@[nospam].fred.net> wrote:
I discovered this when FxCop gave me a Crtical warning about "Do not
declare explicit static constructors". The explanation in the docs is
a bit fluffy so I did some ILDASM exploration.
That's very poor, considering that sometimes you particularly *don't*
want beforefieldinit semantics.
I'm not sure it is such a critical issue in application code (in
framework and library code perhaps it is more of a concern). It would
be nice if beforefieldinit could be explicitly set or removed with a
class level attribute.


Very much agreed.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #16

P: n/a

"Nick Malik" <ni*******@hotmail.nospam.com> wrote in message
news:rRudd.398781$mD.63412@attbi_s02...
I respectfully disagree, Daniel.

The Wiki page that I linked is one of hundreds of pages that call into
question the usefulness, in the long run, of the Singleton pattern.
Perhaps it is, but its probably among the worst. That page is little more
than semi-technical rambling by people who may or may not know what they are
talking about.

No one argument is terribly convincing, no one argument is well formed, ane
no one argument covers all the bases. That page is as much scare tactics as
anything else.

Contrast it with the linked GLobalVariablesAreBad article, I thought that
one was conisderably better.
I believe in "informed consent". That is, if someone is going to
encourage
me to engage in a risky behavior, they should have the integrity to share
the risks with me beforehand. While I don't think it is wise to turn a
valuable technical article into an opinion piece, the OO world has learned
that this pattern is being widely misused... (and others as well,
including
Visitor, apparently). That learning should not be ignored just because
it's
not "technical" in nature.

No, it should not be. However, it also shouldn't be displayed as fact(or in
a way which suggests it is fact) as there is little to no proof provided
there. And again, I made a comment about not requiring a great deal of
research on the part of hte reader. If you start in on this "informed
consent" of yours in articles like Jon's, I fear you risk either becoming
biased towards one opinion or the other, or result in destroying the purpose
of the article trying to maintain the balance between the two and effectivly
swamping out the technical merit.

I do not think an informed decision can be made based only on negative
viewpoints. The wiki, on its own, is not informative, it is simply
inflammatory.
To the contrary, attached to every set of instructions for how to
correctly
use household cleaner, there is a warning label about keeping it away from
children. We should be willing to put a warning label on patterns as
well... especially the ones that get more misuse than others.


*IF* those are actually misused and not just the vendetta of a small number
of loud people. There is an implicit lack of proof that Singletons are bad
and one article mention is not going to achieve that, its just going to make
opinion look like fact.
Nov 16 '05 #17

P: n/a

"Daniel O'Connell [C# MVP]" <onyxkirx@--NOSPAM--comcast.net> wrote in
message news:%2****************@tk2msftngp13.phx.gbl...

"Nick Malik" <ni*******@hotmail.nospam.com> wrote in message
news:rRudd.398781$mD.63412@attbi_s02...
I respectfully disagree, Daniel.

The Wiki page that I linked is one of hundreds of pages that call into
question the usefulness, in the long run, of the Singleton pattern.
Perhaps it is, but its probably among the worst. That page is little more
than semi-technical rambling by people who may or may not know what they

are talking about.
All of us are in the category of people who "may or may not know what they
are talking about."

The wiki page has a long quote from Kent Beck, creator of Extreme
Programming, discussing a major design issue that he refactored out simply
by removing a badly used Singleton. Realize that the C2 wiki is, first and
foremost, a discussion space. You are going to see opinion when you go
there.

No one argument is terribly convincing, no one argument is well formed, ane no one argument covers all the bases. That page is as much scare tactics as anything else.

Contrast it with the linked GLobalVariablesAreBad article, I thought that
one was conisderably better.

OK... here's a better article:
"Why Singletons are Evil"
http://weblogs.asp.net/scottdensmore...25/140827.aspx

or this one
"Perils of the Singleton"
http://www.softwarereality.com/design/singleton.jsp

How about
"Friends don't let friends write singletons"
http://members.capmac.org/~orb/blog....tons.writeback

Here's a list of programming hot-topics, including one titled:
"The Singleton Design Pattern Does More Harm Than Good"
http://www.lisp-p.org/controversy/

I believe in "informed consent". That is, if someone is going to
encourage me to engage in a risky behavior, they should have
the integrity to share the risks with me beforehand.
While I don't think it is wise to turn a
valuable technical article into an opinion piece, the OO world has learned that this pattern is being widely misused... (and others as well,
including Visitor, apparently). That learning should not be
ignored just because it's not "technical" in nature.


No, it should not be. However, it also shouldn't be displayed as fact(or

in a way which suggests it is fact) as there is little to no proof provided
there.
Where's the proof that GOTOs are harmful? Where's the proof that global
variables are harmful? What do you mean by *proof* in this context?

If you actually read some of the information on that is available, on the
web, about Singletons, you will see that the intent was to describe a
"Creational" pattern, while too many people are using it as a "Behavioral"
pattern (e.g. an OO version of a global variable). If global variables are
harmful (and you don't seem opposed to that notion, and if Singletons can be
misused by allowing the creation of global variables in an OO context, then
that misuse should be considered, by reasonable people, to be harmful.
Logic.

If you start in on this "informed
consent" of yours in articles like Jon's, I fear you risk either becoming
biased towards one opinion or the other, or result in destroying the purpose of the article trying to maintain the balance between the two and effectivly swamping out the technical merit.
Give me some credit. A warning is not a slippery slope, denying the reader
of valuable technical content. It is a door to more knowledge that the
reader has the right to walk through, whenever they see fit. Heck... it's
Jon's article, not mine! He's an excellent writer. Do you think he can't
figure out how to strike a balance?

I do not think an informed decision can be made based only on negative
viewpoints. The wiki, on its own, is not informative, it is simply
inflammatory.

The door is open to anyone who would like to investigate further. I didn't
present the best article to the readers who are not familiar with the
debate, and for that I (clearly) could have done a better job. I hope that
the links above mitigate my mistake.
To the contrary, attached to every set of instructions for how to
correctly
use household cleaner, there is a warning label about keeping it away from children. We should be willing to put a warning label on patterns as
well... especially the ones that get more misuse than others.


*IF* those are actually misused and not just the vendetta of a small

number of loud people.
Vendetta? According to dictionary.com, a vendetta is "A bitter, destructive
feud. [Italian, from Latin vindicta, revenge]
Not sure that anyone on the wiki was seeking "revenge" or was "feuding" with
anyone. Considering the fact that the C2 wiki is where many of the modern
discussions of design patterns began, I'm having a hard time imagining these
conversations as being specifically opposed to OO design patterns... they
are merely being honest about the limitations and misuse of one of the most
common patterns.
There is an implicit lack of proof that Singletons are bad
and one article mention is not going to achieve that, its just going to make opinion look like fact.


As I said, I should have provided a better article link. I hope that I did
a better job this time.

--- Nick Malik
http://weblogs.asp.net/nickmalik


Nov 16 '05 #18

P: n/a
> The Wiki page that I linked is one of hundreds of pages that call into > question the usefulness, in the long run, of the Singleton pattern.
>
Perhaps it is, but its probably among the worst. That page is little more than semi-technical rambling by people who may or may not know
what they are talking about.
All of us are in the category of people who "may or may not know what they are talking about."

The wiki page has a long quote from Kent Beck, creator of Extreme
Programming, discussing a major design issue that he refactored out simply by removing a badly used Singleton. > >


That is supposed to be impressive, then?


Not particularly. However, you did note that these folks "may or may not
know what they are talking about". In my mind, you were implying that their
opinion was not useful because you were not aware of any potential
credentials that may lend them credibility. Maybe I misunderstood your
statement. I was only attempting to point out that this objection was
perhaps inconsistent with the content of the specific page.

Opinion is the name of the game, and, IMHO, previously insufficent evidence was presented to base an article warning off of. Y
I agree that the wiki page was, by itself, insufficient to make an argument.
It is a glimpse into a conversation that raged as a debate nearly two years
ago. It's kind of hard to pick up in the middle.
Once I've read the other material I may change my mind, or I may not.
Your thoughtful consideration is more than enough reward for the effort that
comes from responding to a newsgroup, and I am glad of it.
Common practices need to be built on a general consenus, which I have not yet seen.
I agree that common practices need to built on general consensus. The
patterns community largely has reached consensus that the Singleton pattern
is often misused and should be described with sufficient cautions and
warnings to help new readers to avoid common mistakes. You do not need to
take my word on it. Perhaps some of the links I provided will help. You
can also google on the term "Singletons Are Evil" to find more.

I don't particularly like the "NEVER USE GLOBAL VARIABLES OR
ELSE" threats issued in best practices books and articles. They are
inflammatory and without regard for reasons to use global variables and
patterns beyond the OO purists point of view. OO simply isn't everything and shouldn't(perhaps cannot) be shoehorned into every solution. The mere fact
people use singletons and static members is a testimony to that.
I don't know whether to respond to this or not. I don't consider it harmful
for an author to warn their readers away from a practice that they feel will
produce code that is difficult to debug or maintain. Whether or not you
agree with their evaluation of the "offending" practice, we all benefit from
the discussion.

Best practices are best only in the sense that they are ideal. Ideality and the real world don't always coincide. Global variables are fine when they
are appropriate, as are singletons and gotos. No one of them should be
labelled as bad, just particular patterns using them.
Your statement is no more or less "opinion" than those of the people whom
you label "purists." The statement that "nothing is bad" is as much a
valid viewpoint as the statement that "globals are bad" or that "Singletons
are commonly misused." In that same vein, to leave a potentially harmful
practice without a warning is making a statement of opinion just as much as
placing a warning. It is an act of omission. It is still the expression of
an opinion. Ultimately, it is the opinion of the author that always
emerges, and it is the judgement of the reader to accept or reject that
opinion.

A warning is not a slippery slope, denying the
reader of valuable technical content. It is a door to
more knowledge that the
reader has the right to walk through, whenever they see fit. Heck... it's Jon's article, not mine! He's an excellent writer. Do you think he can't figure out how to strike a balance?


Its actually potentially a prod in the direction of an authors opinion
instead of prevailing opinion.


see my comment above about opinions.
I merely stated that some caution
and extra consideration would be a good idea.
I do not disagree with this statement.
I simply
replied that you hadn't offered much in way of suggesting that this is a
warning thats anymore valid than say...a warning that the household cleaner may smell bad. It may be true, but it may not really be a useful one. A
warning is certainly merited if there are real problems, but it is not if it is based entirely on a small selection of people and their particular view
on the world.

It is kind of silly to warn people not to use a hair dryer while sitting in
the bathtub. However, people have done that, and injuries have occurred. A
warning is usually justified if even a small number of poorly educated
people do something that more educated people would scoff at. In
programming, we are not dealing with life and death quite so much, but that
doesn't mean we shouldn't consider using a similar standard.

Yes, anyone can investigate further, they say that with regards to alot of
things(like commercials, for example), but what percentage does? Much in the same way as it would be to mention no negatives at all, it is rather
unbalanced to only reference negative ideas about a given idea in an
article(even if that articles entire purpose is to discredit or discourage
an idea). An article that only points out the flaws in something or goes out of its way to make a point in exposing flaws is particularly untrustworthy, or should be considered as such, IMHO.
Can we move from a discussion of the wiki article itself to a discussion of
Singletons, please? I concede that the wiki article was not a good way to
introduce readers to a discussion that was VERY visible and very heated just
a few years ago. I thought I was reminding folks. I should have been more
careful in respect to people who had missed the earlier discussion
completely.

Again, this isn't to say that Jon can't or won't balance his article well. I am just saying that there is alot more to the picture than simply the
negating side of the argument. I do think, however, that the best course may be to write a seperate article lining out the points and making his
recommendations and linking to *that* from the technical article rather than trying to wedge warnings into the technical article itself and risk
comprimising the article because of it. But, again, thats me.


That is a very good suggestion and one in which I would encourage any
author, including Jon, to consider.

This is a good note to end on.

Thanks for the discussion.
--- Nick
Nov 16 '05 #19

P: n/a
(quick note, consider XP to mean any test driven practice. I didn't clearly
express that and would rather not try to get it right in every circumstance)

That is supposed to be impressive, then?
Not particularly. However, you did note that these folks "may or may not
know what they are talking about". In my mind, you were implying that
their
opinion was not useful because you were not aware of any potential
credentials that may lend them credibility. Maybe I misunderstood your
statement. I was only attempting to point out that this objection was
perhaps inconsistent with the content of the specific page.


Well, for one thing, if the name isn't well known, the credibility is pretty
much non-existant to start with.
Secondly, the more pressing point is that the arguments themselves don't
lend the authors credibility. A big name may sway some people, but its not a
particular good situation when your argument requires your name to hold any
weight.
Anyway, we've agreed that the wiki itself was weak.
On to the other stuff.
Common practices need to be built on a general consenus, which I have not yet seen.


I agree that common practices need to built on general consensus. The
patterns community largely has reached consensus that the Singleton
pattern
is often misused and should be described with sufficient cautions and
warnings to help new readers to avoid common mistakes. You do not need to
take my word on it. Perhaps some of the links I provided will help. You
can also google on the term "Singletons Are Evil" to find more.


In reading these articles, I see a common thread within them. That is most
every person is an XP\Unit testing fan with certain expectations. That is
far from a singluar consenus. That is a small community trying to dictate
what the larger community should do. Some of the constituent ideas are good,
but that doesn't nessecerily mean that the particular communities ideas
inherently are. The argument against singletons outside of unit testing
environments takes a considerable blow
I don't particularly like the "NEVER USE GLOBAL VARIABLES OR
ELSE" threats issued in best practices books and articles. They are
inflammatory and without regard for reasons to use global variables and
patterns beyond the OO purists point of view. OO simply isn't everything and
shouldn't(perhaps cannot) be shoehorned into every solution. The mere
fact
people use singletons and static members is a testimony to that.


I don't know whether to respond to this or not. I don't consider it
harmful
for an author to warn their readers away from a practice that they feel
will
produce code that is difficult to debug or maintain. Whether or not you
agree with their evaluation of the "offending" practice, we all benefit
from
the discussion.


I don't feel its harmful is the purpose of the author was to discuss
potential problems. It, however, is when the author is writing a strictly
technical piece. An article that discusses *how* to write a singleton
correctly is not the proper place to discuss whether singletons are good
practice or not. That is the arena of an opinion piece, not a factual
document. Including such opinions in the context of a technical discussion
will either take merit from the techincal article itself or give false merit
to the opinion. It is potentially unethical, at least to my mind.

Best practices are best only in the sense that they are ideal. Ideality

and
the real world don't always coincide. Global variables are fine when they
are appropriate, as are singletons and gotos. No one of them should be
labelled as bad, just particular patterns using them.


Your statement is no more or less "opinion" than those of the people whom
you label "purists." The statement that "nothing is bad" is as much a
valid viewpoint as the statement that "globals are bad" or that
"Singletons
are commonly misused." In that same vein, to leave a potentially harmful
practice without a warning is making a statement of opinion just as much
as
placing a warning. It is an act of omission. It is still the expression
of
an opinion. Ultimately, it is the opinion of the author that always
emerges, and it is the judgement of the reader to accept or reject that
opinion.


Of course, it is certainly opinion. The more pressing issue, however, is
that I didn't include it in a discussion about how to declare global
variables. Omitting negating opinions is not nessecerily a show of opinion
when the context of the ommission is a situation where the opinion does not
belong.

Every one has opinions and everyone expresses them constantly. Even within
this newsgroup, there are times when i'll reply factually to a question and
then express an opinion along side it. I take extra care to try to seperate
the two into distinct units, but it is not always possible. However, I try
to only express opinoin in an instance of something being done incorrectly,
say someone using a singleton ArrayList(contrived, I know) to perform
sorts.I would strongly suggest a different approach. However, I would not
suggest abandoning singletons if the user wasn't using them in an egregious
manner.

Within the newsgroups, mailing lists, forums, etc we are free to do that
because we can tailor our opinions to the exact situation at hand and choose
only to express them when the situations demands it. Within an article which
is not focused on a given usage of a pattern, but strictly on the technical
information required to get the pattern right on a given platform you cannot
do that and you risk giving confusing or downright incorrect advice. In that
situation you are telling everyone that they are probably wrong, no matter
what their usage is, which isn't what they came looking for.

Again, pointing to a (balanced) best practices document or FAQ on the
subject without an explicit "don't use this" is an entirely different
matter. That allows the author to explain the issues without having to muck
with the techincal issues themselves.
I simply
replied that you hadn't offered much in way of suggesting that this is a
warning thats anymore valid than say...a warning that the household

cleaner
may smell bad. It may be true, but it may not really be a useful one. A
warning is certainly merited if there are real problems, but it is not if

it
is based entirely on a small selection of people and their particular
view
on the world.


It is kind of silly to warn people not to use a hair dryer while sitting
in
the bathtub. However, people have done that, and injuries have occurred.
A
warning is usually justified if even a small number of poorly educated
people do something that more educated people would scoff at. In
programming, we are not dealing with life and death quite so much, but
that
doesn't mean we shouldn't consider using a similar standard.


And I have no problem with that standard. When you are dealing with
pointers, warning that arithmetic errors may cause the application to crash
or behave strangly is one thing, but warning that using a singleton may just
aggervate someone who holds an opinion on singletons is quite another(in my
opinion, the singleton issue is only going to be an issue if some
circumstances are met. It will likely not be an implicit one that is going
to occur in every situation).

Yes, anyone can investigate further, they say that with regards to alot
of
things(like commercials, for example), but what percentage does? Much in

the
same way as it would be to mention no negatives at all, it is rather
unbalanced to only reference negative ideas about a given idea in an
article(even if that articles entire purpose is to discredit or
discourage
an idea). An article that only points out the flaws in something or goes

out
of its way to make a point in exposing flaws is particularly

untrustworthy,
or should be considered as such, IMHO.


Can we move from a discussion of the wiki article itself to a discussion
of
Singletons, please? I concede that the wiki article was not a good way to
introduce readers to a discussion that was VERY visible and very heated
just
a few years ago. I thought I was reminding folks. I should have been
more
careful in respect to people who had missed the earlier discussion
completely.

Discussion of a singleton itself is slightly off topic at this point, I
think. However, I did read through the articles and I saw a few fundamental
flaws:

1) Many of the arguments given are entirely predicated on XP, which is a
terrible way to declare a practice. XP simply is not used widely enough to
consider a problem with XP to be a problem with programming as a whole.
Issues with singletons and XP are the domain of XP and XP articles, not
singletons and singleton articles.

2) The discussion of not knowing what a class is using based on the
signatures is empty minded, to say the least. Classes are entirely capable
of instantiaing objects or performing mischevious casts and other behaviour
to locate quite a bit of information you cannot or will not realize you are
passing in. If you can't see the code you simply cannot know for sure what
the application is actually doing or acting on, period.

3) No argument I've seen yet offers a real solution, just high-handed advice
to redesign your class so it fits a non-singleton design so that you can use
unit testing better. Why not simply redesign your Singleton so that unit
testing is easier instead? Clairty of code is paramount, additional
parameters and deeper callstacks plus additional threading and message
passing to maintain interoperation between instances does not clarify code,
it obfusticates it.

4) The entire concept is highly stooped in OO. OO is not the perfect
paradigm and singletons allow designs to slightly exceed OO's restrictions.
Forcing everything into an OO purist POV is only good for OO purists. For
everyone else it is a hassle they don't want to deal with.

My final thoughts on the negative sides is that these particular users
should switch to entirely functional languages; they will probably be
happier without state of any kind.

Now, for the good points,

1) Careless use of singletons can result in a design that will not scale
across appdomains or complicated component designs and will certainly be a
cause for concern if your application may need to scale up and out at some
point.

2) Many uses of singletons are badly thought out. While configuration is one
I'm not entirely sure of(Trying to create a real linkup between
configuration instance independence and uniform configuration state without
a singleton or non-literal equivilent is a real mess, I've tried it), many
of the other ideas mentioned may well be badly designed.

3) Avoiding singletons(literal static ones and a single instance floating
all over the place) can free your code from locking and other threading
issues. That is a significant simpliciation in its own right.

4) Emphasising factories instead of generic static singletons is a good
idea. The trouble is how to locate factories and how to avoid turning
factories into singleton machines, but that is well beyond the scope of this
discussion.

For the good side, there are certainly good arguments, just not nessecerily
enough to entirely drop the pattern. I do see potential flexibility issues
with singletons and prefer to use service providers when possible, there
simply isnt' any kind of infrastructure available to avoid the use of
singletons without going to extreme ends to provide rarely used
functionality within a component architecture(such as dynamic component to
component discovery and communication). I'm left wondering which is worse, a
tough to test singleton or an easy to test but mostly unnessecery cross
service communication system.

But then that too is well out of the scope of this post. I'd probably have
to spend several hours designing and considering such a system before I
could say which way my mind would end up.
Nov 16 '05 #20

P: n/a
Our common ground appears to be that it would be OK for an author of a
useful technical article (specifically Jon's article on Singletons) to have
a link to a seperate page where the controversy about Singletons could be
discussed as a seperate topic.

Would you agree?

I appreciate the discussion. I really do. And I thank you for the time
you'ved dedicated to discussing this topic. However, I am very stretched
for time these days and I expect that my participation will be low between
now and, oh, November 3rd...

--- Nick

Nov 16 '05 #21

P: n/a

"Nick Malik" <ni*******@hotmail.nospam.com> wrote in message
news:7mted.235935$wV.93009@attbi_s54...
Our common ground appears to be that it would be OK for an author of a
useful technical article (specifically Jon's article on Singletons) to
have
a link to a seperate page where the controversy about Singletons could be
discussed as a seperate topic.

Would you agree?
Yes, as long as the joining article isn't written strictly with the intent
of discrediting singletons, in this case. It should let the user make up
their own mind as much as possible.

I appreciate the discussion. I really do. And I thank you for the time
you'ved dedicated to discussing this topic. However, I am very stretched
for time these days and I expect that my participation will be low between
now and, oh, November 3rd...

Yes, yes, that happens, ;).

Anyway, as has been mentioned, the discussion benefits everyone. I imagine
there were others beyond you, me, and Jon reading this article.

Nov 16 '05 #22

This discussion thread is closed

Replies have been disabled for this discussion.