In what situations is static method a good practice?

后端 未结 11 1055
走了就别回头了
走了就别回头了 2020-12-04 10:04

I have read the following discussions:

Should private helper methods be static if they can be static , and
Should all methods be static if their class has no mem

11条回答
  •  感动是毒
    2020-12-04 10:57

    Think of this for a moment. In OO coding, every single function call actually looks like this:

    method(object this, object arg1, object arg2) where this is the object you are calling. All it really is is syntax sugar for this. Additionally it allows you to clearly define scope of variables because you have object variables etc.

    Static methods simply don't have a "this" parameter. Ie you pass variables in and possibly get a result back out. 1.) is the main reason people avoid them, you can't create an interface to a static method (yet) so you can't mock out the static method to test it.

    Secondly OO are procedures functions etc. Static methods make a lot of sense in certain situations, but they can always be made into a method on an object.

    Mind you, you couldn't remove this without a hack:

    static void Main(string[] args)
    {
    }
    

    The code that starts your application MUST be callable WITHOUT a reference to an object. So they give you flexibility, whether you choose to use them in your scenario will be predicated by your requirements.

提交回复
热议问题