A magic number is a direct usage of a number in the code.
For example, if you have (in Java):
public class Foo {
public void setPassword(String password) {
// don't do this
if (password.length() > 7) {
throw new InvalidArgumentException("password");
}
}
}
This should be refactored to:
public class Foo {
public static final int MAX_PASSWORD_SIZE = 7;
public void setPassword(String password) {
if (password.length() > MAX_PASSWORD_SIZE) {
throw new InvalidArgumentException("password");
}
}
}
It improves readability of the code and it's easier to maintain. Imagine the case where I set the size of the password field in the GUI. If I use a magic number, whenever the max size changes, I have to change in two code locations. If I forget one, this will lead to inconsistencies.
The JDK is full of examples like in Integer
, Character
and Math
classes.
PS: Static analysis tools like FindBugs and PMD detects the use of magic numbers in your code and suggests the refactoring.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…