Should C# methods that can be static be static?
We were discussing this today and I'm kind of on the fence. Imagine you have a long method that you refactor a few lines out of. The new method probably takes a few local variables from the parent method and returns a value. This means it could be static.
The question is: should it be static? It's not static by design or choice, simply by its nature in that it doesn't reference any instance values.
Not necessarily.
Moving public methods from static to non-static is a breaking change, and would require changes to all of your callers or consumers. If a method seems like an instance method, but happens to not use any instance members, I would suggest making it an instance method as a measure of future-proofing.
Yes, it should. There are various metrics of coupling that measure how your class depends on other things, like other classes, methods, etc. Making methods static is a way to keep the degree of coupling down, since you can be sure a static method does not reference any members.
Yes. The reason "it can be static" is that it does not operate on the state of the object upon which it is called. Therefore it is not an instance method, but a class method. If it can do what it needs to do without ever accessing the data for the instance, then it should be static.
As long as you make the new method private static it is not a breaking change. In fact, FxCop includes this guidance as one of its rules (http://msdn.microsoft.com/en-us/library/ms245046(VS.80).aspx), with the following information:
That being said, the first comment from David Kean more succinctly summarizes the concerns by saying this is actually more about being correct than about the performance gain:
Inherently static methods that are for some reason made non-static are simply annoying. To wit:
I call my bank and ask for my balance.
They ask for my account number.
Fair enough. Instance method.
I call my bank and ask for their mailing address.
They ask for my account number.
WTF? Fail—should have been static method.
Static methods are faster than the non-static ones so yes, they should be static if they can and there is no special reason for leaving them nonstatic.