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.
You should think about your methods and classes:
If the last two are 'yes', then your method/class should probably be static.
The most used example is probably the
Math
class. Every major OO language has it and all the methods are static. Because you need to be able to use them anywhere, anytime, without making an instance.Another good example is the
Reverse()
method in C#.This is a static method in the
Array
class. It reverses the order of your array.Code:
It doesn't even return anything, your array is reversed, because all arrays are instances of the Array class.
It depends but generally I do not make those methods static. Code is always changing and perhaps someday I will want to make that function virtual and override it in a subclass. Or perhaps some day it will need to reference instance variables. It will be harder to make those changes if every call site has to be changed.
I'm in the "only make private methods static" camp. Making a public method can introduce coupling that you don't want and may decrease testability: You can't stub a public static method.
If you want to unit test a method that uses a public static method, you end up testing the static method as well, which might not be what you want.