Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 568
Khanzor Avatar asked Feb 07 '11 23:02

Khanzor


People also ask

Should you ever use static methods?

You should consider making a method static in Java : 1) If a method doesn't modify the state of the object, or not using any instance variables. 2) You want to call the method without creating an instance of that class.

Should I avoid static methods?

Static methods are bad for testability. Since static methods belong to the class and not a particular instance, mocking them becomes difficult and dangerous. Overriding a static method is not that simple for some languages.

Which is better static or non static method?

A static method cannot be overridden being compile time binding. A non-static method can be overridden being dynamic binding. Static method occupies less space and memory allocation happens once. A non-static method may occupy more space.

Why are static methods better?

They are faster — Static methods are slightly faster than instance methods because in instance methods, you are also working with an implicit this parameter. Eliminating that parameter gives a slight performance boost in most programming languages.


2 Answers

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!

like image 138
Eric Lippert Avatar answered Sep 22 '22 03:09

Eric Lippert


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.

like image 43
recursive Avatar answered Sep 21 '22 03:09

recursive