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.
One reason you might want to declare static helper methods is if you need to call them in the class constructor "before"
this
orsuper
. For example:This is a bit of a contrived example but clearly
recoverInt
cannot be an instance method in this case.The static/non-static question comes down to "will I really need to use an object of this class"?
So, are you passing the object between different methods? Does the object contain information that is useful outside the context of the static methods? Is there any reason not to define methods both ways if you'll use them both ways?
If you're in this dilemma, it seems to me that you have all of the data required for the method floating around in your code outside of the object. Is this what you want? Would it be easier to just always collect that data into an object each time? You might just be ambivalent about committing to a single model. If you can do it all using one way, then pick either static or non-static and go with it.
More specifically to the example you've given, it seems that the purpose of defining these methods is more for code clarity when you're reading it than for functionality (they are defined as private). In that case, going with static really does nothing for you, since the purpose of static is to expose class functionality.