What Are Static Classes/Methods For?
Moderator: General Moderators
- Jonah Bron
- DevNet Master
- Posts: 2764
- Joined: Thu Mar 15, 2007 6:28 pm
- Location: Redding, California
What Are Static Classes/Methods For?
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?
- John Cartwright
- Site Admin
- Posts: 11470
- Joined: Tue Dec 23, 2003 2:10 am
- Location: Toronto
- Contact:
Re: What Are Static Classes/Methods For?
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.
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?
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?
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.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.