Let's say I have a class designed to be instantiated. I have several private "helper" methods inside the class that do not require access to any of the class members, and operate solely on their arguments, returning a result.
public class Example {
private Something member;
public double compute() {
double total = 0;
total += computeOne(member);
total += computeMore(member);
return total;
}
private double computeOne(Something arg) { ... }
private double computeMore(Something arg) {... }
}
Is there any particular reason to specify computeOne
and computeMore
as static methods - or any particular reason not to?
It is certainly easiest to leave them as non-static, even though they could certainly be static without causing any problems.
I can't really think of clear advantages for private static method. That being said, there is no specific advantages to making them non-static either. It's mainly a matter of presentation : you might want to make them static to clearly underline the fact that they are not altering an object.
For method with different access privileges, I think there are two main arguments :
Besides that, the difference is pretty small, and I strongly doubt that the extra this pointer passed to instance method makes a significant difference.
Off-Topic: I'd keep the helper methods in a standalone utility/helper class with only static methods in it.
The trouble with having helper methods at the point of use ( read 'same class' ) is that someone down the line may just choose to post their own unrelated helper methods in the same place
Correct Answer is:
any method which does not take any information from a field, and does not put any information into a field, does not have to be an instance method. Any method which does not use or alter any fields in its class or object might as well be a static method.
My preference in cases like these is to make
computeOne
andcomputeMore
static methods. The reason: encapsulation. The less code which has access to the implementation of your class, the better.In the example you give, you state that
computeOne
andcomputeMore
shouldn't need to access the internals of the class, so why give the opportunity for maintainers of the class to meddle with the internals.One issue about having static methods is that it can make the object more difficult to use in unit tests. Mockito can't create mocks for static methods and you can't create a subclass implementation of the method.
I prefer such helper methods to be
private static
; which will make it clear to the reader that they will not modify the state of the object. My IDE will also show calls to static methods in italics, so I will know the method is static without looking the signature.