double potentialEnergy(double mass, double height) { return mass * height * 9.81; }
double potentialEnergy(double mass, double height) { return mass * GRAVITATIONAL_CONSTANT * height; } static final double GRAVITATIONAL_CONSTANT = 9.81;
For more information see page 204 of Refactoring
For this refactoring I used a symbolic constant, which is the most common Java idiom.
However an alternative is the constant method, which is a method of this form
public static double gravitationalConstant() { return 9.81; }
This idiom is less familiar to C based programmers, but is very familiar to Smalltalkers (who didn't have constants in their language). On the whole I don't tend to use this in Java as it is less idiomatic to the language. However if you need to replace the simple return with a calculated value then it's worth changing the constant field to a constant method. (I guess there should be a refactoring for that....)