Should I prefer static methods in C#

前端 未结 6 1342
一整个雨季
一整个雨季 2021-02-05 08:47

Having spent a bit of time learning about functional programming, it\'s becoming more and more natural for me to want to work with static methods that don\'t perform any mutatio

相关标签:
6条回答
  • 2021-02-05 09:05

    Great question.

    I think the answer depends on the context of what your code does, and how much of it is static.

    My code has been seeing less static cases since I program to interfaces a lot now and mark some methods 'protected virtual' rather than 'static' for cases such as unit testing's extract and override pattern. Thats not to say you couldnt just call static methods from those, though.

    0 讨论(0)
  • 2021-02-05 09:09

    Not completely. I do like my extension methods, and Linq, but an OO-language should be used in an OO fashion. Besides, it's all imperative at the CPU, and for several layers on top of that.

    0 讨论(0)
  • 2021-02-05 09:10

    You can write working programs this way, but it's not idiomatic. If you want to work on a team, I'd try to curb it. If no one else is reading your code, go nuts.

    0 讨论(0)
  • 2021-02-05 09:12

    There is many reasons should curb this instinct when you write OOP.

    Object states and behaviours;

    Static class and method need parameters, and you should be sure which paramters will pass to static methods. But class manages itself if method related with is state.

    I think that only this reason enough to curb static modifiers.

    And for clear reason, we should listen Mrs. Liskov. here

    0 讨论(0)
  • 2021-02-05 09:15

    The question I find a bit odd, because static methods and methods that perform no mutations are two orthogonal classifications of methods. You can have mutating static methods and nonmutating instance methods.

    For me, it has become more and more natural to combine functional and oo programming; I like instance methods that perform no mutations. Functional programming is easier to understand because it discourages complex mutations; OO programming is easier to understand because the code and the data it operates on are close together. Why choose? Embrace the power of "and"; do both!

    0 讨论(0)
  • 2021-02-05 09:17

    For some reason I think of this quote when I read your question:

    You can write Fortran in any language.

    If the intent of C# were to be purely functional, static would be unnecessary because everything would be static by default. If you are strict about following OOP practices and the SOLID principles, your code effectively becomes functional (I know there's a quote out there about this somewhere) so you end up getting the best of both worlds.

    The reason I would curb it in a multi-user project would be that it's not typical C# (it's really C# with handcuffs). You just need one person to break the rule and declare a static mutable property and everything goes to hell.

    0 讨论(0)
提交回复
热议问题