Suppose I have a class like this:
public class Car {
private double distanceDriven;
public void drive(double miles){
distanceDriven += miles;
}
public void driveInCanada(double kilometer){
distanceDriven += convertToMiles(kilometer);
}
private double convertToMiles(double km){
return km*0.621371192;
}
}
You can see that convertToMiles is:
- not using any instance variables
- is only used inside the class
Should it be declared as static? This does not change the functionality of the the function at all (see above). I think that it may affect:
- readability
- performance
- other?
Should the convertToMiles function look like:
private double convertToMiles(double km){
or
private static double convertToMiles(double km){
For maximum stylistic hygiene, yes, private methods that don’t use any object state, but only make sense inside the object, should be static.
That’s the clearest (and strictest) way of indicating how they operate, and it will helpfully force you to be careful about your design around method-boundaries, and to think twice if you decide to go change one of them later to use object data.
FWIW, I don’t suspect there’s a relevant performance impact here (in theory the static is easier to call due to no implicit
thisreference). Also, you could go nuts being strict about this in your codebase, but it’s certainly a reasonable goal to have.N.B. Public methods require more consideration before marking them static; those can’t change down the road without impact to callers, so “defaulting to tightness” isn’t always the right choice.