Should C# methods that *can* be static be static?

2019-01-04 21:33发布

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.

21条回答
再贱就再见
2楼-- · 2019-01-04 22:24

You should think about your methods and classes:

  • How are you going to use them?
  • Do you need a lot of acces to them from different levels of your code?
  • Is this a method/class I can use in almost every thinkable project.

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:

public static void Reverse(Array array)

It doesn't even return anything, your array is reversed, because all arrays are instances of the Array class.

查看更多
Juvenile、少年°
3楼-- · 2019-01-04 22:25

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.

查看更多
smile是对你的礼貌
4楼-- · 2019-01-04 22:27

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.

查看更多
登录 后发表回答