What is a magic number, and why is it bad?

[java]
public class Foo {
public void setPassword(String password) {
// don’t do this
if (password.length() > 7) {
throw new InvalidArgumentException(“password”);
}
}
}
[/java]
[java]
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”);
}
}
}
[/java]
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. more

You may also like

Dodaj komentarz

Twój adres email nie zostanie opublikowany. Pola, których wypełnienie jest wymagane, są oznaczone symbolem *