简体   繁体   中英

Should I prefer static methods in C#

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 mutation.

Are there any reasons why I should curb this instinct?

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!

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.

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.

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM