Page 1 of 1

What Are Static Classes/Methods For?

Posted: Sun Feb 13, 2011 12:26 pm
by Jonah Bron
I'm just wondering, what are static classes/methods actually for? The only application I can think of is a singleton. Otherwise, when is a good time for a static class?

Re: What Are Static Classes/Methods For?

Posted: Sun Feb 13, 2011 2:01 pm
by John Cartwright
Factories, registries, etc.

Basically, anytime you want to maintain a single instance of something (an object, array, etc) static is a likely candidate. It's generally best to avoid static's when possible, since they are harder to test, and remove the possibility of dependency injection, however, they are extremely useful as helper methods.

Re: What Are Static Classes/Methods For?

Posted: Mon Feb 14, 2011 3:35 am
by Darhazer
By definition, the static method, and the static members, belong to the class itself, and not to it's instance. The static methods have to be stateless - they should not depend on any previous calls to the method or to other static methods. You can have a static method if it fits in the above description and you want to provide it's functionality without need to have an instance of the object (if you will use the functionality only with the object's instance, there is no need to make the function static).

Re: What Are Static Classes/Methods For?

Posted: Mon Feb 14, 2011 10:17 am
by pickle
I use static classes whenever I only ever need to do one thing with the class. An email sending class for example, or an error recording class.