>I completely agree with you. All the reasons you named are valid ones.
>But notice you did not mention "can mock out" as a reason.

In a way I did. "Mocking out" and "mock object" are Extreme Programming
terms for what others call a "service stub." In object oriented languages,
these patterns typically rely on the ability for objects to behave
polymorphically, which a static class cannot do. This is achieved through
the use of an abstract singleton base class.

>Where do you draw the line between trivial/non-trivial?

The $64,000 question.

>Why not use a singleton everywhere and be consistent?

You could, there's no reason not to. A simple singleton is insanely easy to
code in .NET.

>Utility classes should be static but as soon as you need to keep some
>sort of state, then a singleton should be preferred I think, for all
>the reason you gave and more (eg can implement interface).

I actually don't see state as a criteria for deciding between a singleton
and a static class. Static member variables are essentially identical to a
static member's intance variables.

I really think that it's a matter of needing to make use of language
features that require object oriented principles (like the previously
mentioned polymorphism, or encapsulation, inheritence, etc. ), or complete
control of an object's lifecycle. The "mocking out" practice is a perfect
example of this.

If you don't need any object oriented features, or control over object
lifecycle, skip the singleton pattern, and go with a static class.

>You should also make the singleton class sealed, otherwise I think a
>factory is a better choice.

I'm not sure what you mean here... my understanding of the factory pattern
is that it is independent from a singleton. Many times a factory is
implemented as a singleton, but that doesn't mean it has to be.

In my view, the issue as to weather or not to seal a singleton class is
totally singleton specific. I actually feel like, if you have a situation
where you are trying to seal a singleton, that's actually a case where a
static class might work just as well.

My feeling is that a singleton is not always the BEST choice, but never the
wrong choice, while a static class might be the best choice, but could also
be the wrong choice.

Just to contradict this, my strategy is generally to start with a static
class, and then convert to a singleton later if I start needing object
oriented stuff. This is because I'm lazy, and the conversion is rarely painful.

Hope this helps,
Luke

===================================
This list is hosted by DevelopMentor®  http://www.develop.com

View archives and manage your subscription(s) at http://discuss.develop.com

Reply via email to