Making Methods All Static in Class

前端 未结 10 1261
离开以前
离开以前 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:31

    Make sure that you have a good reason to make class static.

    According to Framework Design Guidelines:

    Static classes should be used only as supporting classes for the object-oriented core of the framework.

    DO NOT treat static classes as a miscellaneous bucket.

    There should be a clear charter for the class.

    0 讨论(0)
  • 2021-01-04 12:33

    As long as you don't need to create any abstraction from your class then static methods are fine. If your class needs to be mocked or implement any sort of interface then you're better off making the class a singleton, since you cannot mock static methods on classes. You can have a singleton implement an interface and can inherit instance methods from a singleton whereas you cannot inherit static methods.

    We generally use singletons instead of static methods to allow our classes to be abstracted easily. This has helped in unit testing many times since we've run into scenarios where we wanted to mock something and could easily do so since the behavior was implemented as instance methods on a singleton.

    0 讨论(0)
  • 2021-01-04 12:39

    Most of the time it's OK to make the class static. But a better question is why do you have a class without state?

    There are very rare instances where a stateless class is good design. But stateless classes break object oriented design. They are usually a throwback to functional decomposition (all the rage before object oriented techniques became popular). Before you make a class static, ask yourself whether the data that it is working on should be included int he class or whether all of the functionality in the utility class shouldn't be broken up between other classes that may or may not already exist.

    0 讨论(0)
  • 2021-01-04 12:42

    Utility classes are often composed of independant methods that don't need state. In that case it is good practice to make those method static. You can as well make the class static, so it can't be instantiated.

    With C# 3, you can also take advantage of extension methods, that will extend other classes with those methods. Note that in that case, making the class static is required.

    public static class MathUtil
    {
        public static float Clamp(this float value, float min, float max)
        {
            return Math.Min(max, Math.Max(min, value));
        }
    }
    

    Usage:

    float f = ...;
    f.Clamp(0,1);
    
    0 讨论(0)
提交回复
热议问题