Making Methods All Static in Class

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

    I can think of lots of reasons for a non-static class with no members. For one, it may implement an interface and provide/augment behavior of another. For two, it may have virtual or abstract methods that allow customization. Basically using 'static' methods is procedural programming at it's worst and is contrary to object-oriented design.

    Having said that, often small utilities routines are best done with a procedural implementation so don't shy away if it make sense. Consider String.IsNullOrEmpty() a great example of a procedural static routine that provides benefit in not being a method. (the benefit is that it can also check to see if the string is null)

    Another example on the other side of the fence would be a serialization routine. It doesn't need any members per-say. Suppose it has two methods Write(Stream,Object) and object Read(Stream). It's not required that this be an object and static methods could suffice; however, it make sense to be an object or interface. As an object I could override it's behavior, or later change it's implementation so that it cached information about the object types it serialized. By making it an object to begin with you do not limit yourself.

提交回复
热议问题