Replace Magic Number with Symbolic Constant


You have a literal number with a particular meaning.

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;
        }


        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)
Posted by 아름프로
BLOG main image

카테고리

분류 전체보기 (539)
이야기방 (19)
토론/정보/사설 (16)
IBM Rational (9)
U-IT (0)
SOA/WS/ebXML (110)
개발방법론/모델링 (122)
J2SE (34)
J2EE (60)
DataBase (39)
Open Projects (30)
BP/표준화 (50)
Apache Projects (15)
Web/보안/OS (22)
Tools (7)
AJAX/WEB2.0 (1)
Linux/Unix (1)
영어 (0)
비공개방 (0)

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

달력

«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28

글 보관함

Total :
Today : Yesterday :