Should I prefer static methods in C#

1.4k views Asked by At

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?

6

There are 6 answers

0
Eric Lippert On BEST ANSWER

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
CRice On

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.

1
recursive On

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.

6
Nuri YILMAZ On

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
KeithS On

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
Austin Salonen On

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.