What variables do you weigh when considering a static class?
I have a static class that I think needs to be refactored into an instance class, because the design has changed and I need to consume it in another class (passed by param).
I am thinking I should have designed it as an instance class to begin with; what factors do you evaluate when you decide?
-
-
You would usually use a static class as a "factory". It usually doesn't have any state associated with it, all it does is produce other classes. It would usually have the controller type of behaviour.
That's my take on it anyway.
-
phreaks wrote:I am thinking I should have designed it as an instance class to begin with; what factors do you evaluate when you decide?
Simple method right here:
if( Is your class state-ful? ) {
goto InstanceClass;
} else {
goto StaticClass;
}
Or just think back to VB6 days with "Modules", if it would be in a VB6 module then it's in a static class now (in fact, VB.NET Modules are compiled to CIL Static Classes)
-
I only create static classes for factories, and for bundling useful functions that don't fit elsewhere (StringUtils, XmlUtils, Conversion, ...)
-
Agree with above. Static classes are instanced upon execution of the assembly, and remain that single instance in the heap. For what often amounts to utility methods implementing the functionality within static methods/classes makes sense for performance reasons.
-
W3bbo wrote:
Simple method right here:
if( Is your class state-ful? ) {
goto InstanceClass;
} else {
goto StaticClass;
}
Or just think back to VB6 days with "Modules", if it would be in a VB6 module then it's in a static class now (in fact, VB.NET Modules are compiled to CIL Static Classes)
I'd probably mangle that method a bit more:
if( Is your class state-ful? )
{
if( WouldBeSingletonIfYouEverUsedSingletonsAndDon'tHateTheConcept )
{
goto StaticClass:
}
else
{
goto InstanceClass;
}
}
else
{
goto StaticClass;
}
Yeah, I use Static classes as Singletons whenever I can. Saves a lot of effort. (and yes, I hate the idea of singleton classes, but sometimes they do reflect a physical reality.)
Often not suitable for libraries though
-
I only use static classes when defining factory classes, helper classes, ulitily classes for classes which only contain interop methods declaration.
Sheva
Thread Closed
This thread is kinda stale and has been closed but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know.