Sometimes when writing a class you'll need some helper methods that take care of some simple stuff (change a string in a certain way or do some simple calculations).
If helper functionalities are small enough (and not needed by any other class) it makes sense to write a helper method in this class.
Now: assuming you'll need no access to any member variables, would it be better do make this method private
or private static
the following example: just implements a method that checks if a string is not null
and contains foo.
public class SomeClass
...
public void calculate(String inputString) {
...
boolean foo = getFoo(inputString);
}
private (static) boolean getFoo(String inputString) {
return inputString != null && inputString.contains("foo");
}
}
Are there pros and cons in making the method static or non-static. Is there a general do and don't?
I would personally make the method static - it makes it clearer that it doesn't depend on the state of the object. That can have knock-on effects in terms of thread safety (although if it were to access static members of the type, you'd need to be careful of that).
Given that it's private, you don't need to worry about whether or not subclasses would want to override it.
You can always make it non-static later - I think the only side-effect of that would be to potentially change the serialization ID. (Binary serialization is a pain like that.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With