Replace Magic Number with Symbolic Constant <IMG SRC = "http://www.refactoring.com/catalog/updated.gif" border=0>
2003. 8. 2. 15:19
Replace Magic Number with Symbolic Constant
Create a constant, name it after the meaning, and replace the number with it.
double potentialEnergy(double mass, double height) {
return mass * height * 9.81;
}
![](http://www.refactoring.com/catalog/arrow.gif)
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
Additional Comments
Using a constant method
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....)
Contributors
- Jutta Eckstein
***** 아름다운프로님에 의해서 게시물 복사 + 카테고리변경되었습니다 (2003-12-18 17:27)