Creating framework for singleton pattern?

G

Guest

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?
 
J

Jon Skeet [C# MVP]

Sharon said:
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.
 
R

Robert Jordan

Sharon said:
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
 
R

Richard Blewett [DevelopMentor]

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.
 
N

Nick Malik

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
 
R

Richard Blewett [DevelopMentor]

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.
 
D

Daniel O'Connell [C# MVP]

Jon Skeet said:
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.
 
J

Jon Skeet [C# MVP]

Richard Blewett said:
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
 
R

Richard Blewett [DevelopMentor]

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 said:
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:
 
J

Jon Skeet [C# MVP]

Richard Blewett said:
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.
 
N

Nick Malik

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
 
R

Richard Blewett [DevelopMentor]

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 said:
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.
 
S

Scott Allen

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.
 
J

Jon Skeet [C# MVP]

Scott Allen said:
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.
 
D

Daniel O'Connell [C# MVP]

Nick Malik said:
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.
 
N

Nick Malik

Daniel O'Connell said:
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/archive/2004/05/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.cgi/tech/coding/no_singletons.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/

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.
*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
 
D

Daniel O'Connell [C# MVP]

Nick Malik said:
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.

That is supposed to be impressive, then?

Opinion is the name of the game, and, IMHO, previously insufficent evidence
was presented to base an article warning off of. You might be able to win
the case(I've not put enough thought into the specific issues to comment),
but it takes significantly more than just a wiki to address that. Once I've
read the other material I may change my mind, or I may not. Common practices
need to be built on a general consenus, which I have not yet seen.
OK... here's a better article:
"Why Singletons are Evil"
http://weblogs.asp.net/scottdensmore/archive/2004/05/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.cgi/tech/coding/no_singletons.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/



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?

There is no hard evidence in any of these cases. And issues with goto and
globals are mostly blown out of proportion by people selling conventions.
Believe it or not, every now and then I run into a circumstance where one or
the other may make cleaner code. However, because of best practices and
patterns people, I end up with messier code trying to avoid what I know will
result in whining from someone.
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.

You didn't ask about globals, that I can remember anyway. I did comment that
I felt the global variables are bad article was a bit better example of a
good link than the anti-singletons one was.

Global variables, in and of themselves, are not harmful. Perhaps some usage
of them is questionable. But then some usages of the if statement are
questionable. 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.

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(and, generally, only
those patterns which are superceded by others. Using goto to implement else,
for example, should be frowned upon. Using goto to exit 30 block levels
perhaps should not be. It is arguably clearer than 30 if statements checking
a guardian boolean).
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?

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

And, I suspect Jon certainly can and will balance his article, but he left
this discussion some time ago it seems. I merely stated that some caution
and extra consideration would be a good idea. You were the one that started
this particular subthread by suggesting that the warning was appropriate,
infact on the level of household cleaner poison warning labels. 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.

The question I pose is that, without considerable research and
consideration, is it proper and the best course to offer advice against
singletons from a page as commonly quoted and as well respected as Jon's
article?
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.

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.

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.

*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]

The meaning I intended was the one used in "personal vendetta", that is, the
particular participants have issues with Singletons or one persons
particular use of singletons and are out to eliminate or discredit them. A
great deal of the computer science world works this way, it'd be silly to
think that anything is implicitly immune.
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.

And again, that doesn't matter. That is almost innocence by association.
Just because it was on the C2 wiki doesn't make it any more correct or
proper than if it was on some two bit forum elsewhere. The people in the
discussion may well dislike the pattern enough to try to eliminate it
without a valid reason.

Also, as far as design patterns go, they are a take some and leave the rest
kind of thing. Many patterns are strong, yet some are lame, others uselss,
and many are way overused(like the NullObject pattern, for one). Simply
calling it a design pattern doesn't nessecerily make it right, it just makes
it someones opinion that they felt like publishing. It is far more a matter
of what you agree with than of who said it.
As I said, I should have provided a better article link. I hope that I
did
a better job this time.

I'll read them tomorrow and let you know. It is getting a touch late for
serious reading, methinks.
 
J

Jon Skeet [C# MVP]

And, I suspect Jon certainly can and will balance his article, but he left
this discussion some time ago it seems.

Fear not, I'm watching it with interest from the sidelines...
 

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

Top