Making Methods All Static in Class

前端 未结 10 1329
离开以前
离开以前 2021-01-04 12:10

I was told by my colleague based on one of my classes (it is an instance class) that if you have no fields in your class (backing fields), just make all methods static in th

10条回答
  •  轮回少年
    2021-01-04 12:24

    A lack of state alone is no reason to make methods static. There are plenty of cases where a stateless class should still have instance methods. For example, any time you need to pass specific implementations of some logic between routines, it's much easier to do it with classes that have instance methods, as it allows us to use interfaces:

    interface IConnectionProvider
    {
        object GetConnectedObject();
    }
    

    We could have a dozen implementations of the above, and pass them into routines that require an IConnectionProvider. In that case, static is a very clumsy alternative.

    There's nothing wrong with having to use new to use a method in a stateless class.

提交回复
热议问题