Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you not use static methods for all private methods?

Tags:

.net

static

I'm trying to understand static methods and I've reached a confusing point.

Focusing only on methods for this question, if I create an instance of my object (where the class itself is not static) then I typically only have access to the public, protected and or internal methods (depending on scope/encapsulation). In other word, I don't have access to private methods.

I've read that, although minimal, static methods are slightly more efficient than non-static methods.

So, when creating a private method with a return type of void, and excluding when you're creating a reference of an object from within itself, why would you ever not make it static? All the code I've ever seen doesn't do this, so I can only assume I've missed the point.

like image 315
Dave Avatar asked May 14 '13 13:05

Dave


3 Answers

Static methods cannot access the non-static member data in the class.

like image 184
Bathsheba Avatar answered Nov 10 '22 02:11

Bathsheba


Static methods are typically supposed to be stateless and therefore have no access to the instance state. In contrast, instance methods are stateful and can therefore read and modify the instance's state.

Typical examples of stateless methods are:

  • Factory Methods
  • Binary Operators
  • ...

Of course, static methods aren't always stateless though, there are samples of static stateful methods. There is one single state for the class then:

  • Singleton
  • Instance Pools
  • ...

These implementations need slightly more care though, since the class's state is also shared by all threads within the process.

like image 26
Matthias Meid Avatar answered Nov 10 '22 02:11

Matthias Meid


I've read that, although minimal, static methods are slightly more efficient than non-static methods.

That's not unconditionally true: only the methods that could otherwise be static but are not made static by omission would be more efficient. Otherwise, you would need to pass a reference to the object manually, leveling up the playing field. Moreover, CLR is optimized so much that the difference is hard to measure.

To answer your question, there is no reason to make a method non-static if it does not access instance state through properties or variables. However, all methods that access per-instance state should be non-static for readability, because there is no performance to gain from making them static and passing the instance manually.

To illustrate the point, you should do this

private void AddCount(int number) {
    current += number;
}

rather than this:

// Do not do this!
private static void AddCount(MyClass obj, int number) {
    obj.current += value;
}
like image 35
Sergey Kalinichenko Avatar answered Nov 10 '22 01:11

Sergey Kalinichenko