3

I have a private helper method that uses no instance variables or methods, I feel it would be less confusing if it was static (this way, it's given fewer points it can access).

I am a bit unsure if this question applies to private methods too.

I've also taken a look at this second question but again testing is not going to test private static helper methods directly.

Question: Why shouldn't I make my private helper methods static? Is it the confusion that would maybe lead someone to reuse it in a static context? As far as I see, that should be fine.

Any thoughts and suggestions are appreciated.

user85190
  • 133

2 Answers2

7

The widespread antipathy towards static methods is largely due to fear that you won't be able to override a method easily for testing the class or mocking to test another class.

With a private method this isn't a concern, so my opinion is: if it can be static, make it static - this acts as a useful bit of automatic documentation ("this method does not depend on any instance state at all"). You shouldn't rewrite helper methods so that the become static-capable (e.g. by replacing field access with input parameters), but if this is its natural form then there's no harm and a little bit of gain.

Kilian Foth
  • 110,899
3

To answer this, we should clarify the definition of static:

Static methods are meant to be relevant to all the instances of a class rather than to any specific instance. They are similar to static variables in that sense. An example would be a static method to sum the values of all the variables of an instance for a class. For example, if there were a Product class it might have a static method to compute the average price of all products.

Any static method can become a non-static method, so being static makes a statement about the impact calling such a method would have on your instance, which is to say none unless of course you were passing said instance to the static method (thus defeating the purpose of being static).

This method holds no state to do its job properly and could refer to any instance, so I would say yes, you should make it static. However do be sure to leave it also private, since it is a method that only makes sense in the context of your class, and until that changes, it should remain private.

If you find yourself with several such private static helper methods, you should consider creating a final class with private constructor containing only protected static methods, which can only be called by classes in your package.

I hope that answers your question.

Neil
  • 22,848