I noticed in a custom base class that we use for a lot of our web pages we have a few static methods. Since the class is being used as a base class for web pages what benefit would it have making the methods static? I’m thinking none but wanted verification.
Also in custom base class we have properties that call other static methods in a manager class of ours in another class library and returns either a DataTable or HashTable.
I can see where as a convenience factor for devs to code against but other than that is their any reason for making the methods static in there as well?
So existing code looks something like this:
public class CustomBaseClass
protected Hashtable displayText
{
get{
if(_displayText == null)
displayText = MyManager.GetCustomersList(sCustID);
since GetCustomersList is static every method inside this method has to be static as well. All the way down to our data access layer. Just seems odd to me coding it this way but was curious as to what you all thought.
Our old developers who coded our application are gone and they use them all over the place. Is their any negatives or watch out fors to using static methods especially in an asp.net app?
If I create a singleton wouldn’t that make more sense, then I wouldn’t have to make all the method calls right down to our DAL static? lol
The main reason to make a method static typically is when it does not depend on any instance members of the class. The avoids having to create a new instance of the class to call the method, which then needs to be garbage collected later.
Both static and instance methods obviously have their place. Typically I create static methods for utility methods that get all their state from either static members (though you have to synchronize of course) or parameters, or to set a class-wide property for all instances of the class.
You can use a singleton (though some folks hate them), or you can just have your DAO objects created at the highest level class and injected further down, of course.
The main problem with using static methods, is that while it’s very easy to unit test static methods, it can be more difficult to mock the results from calls to a static DAO class. It’s much easier to mock if it’s an injected instance.