定义常量来代替魔术数字,并将常量用于代码中。
例如,在填充以下示例的对象时,我们可以使用常量替换魔术数字:
public void fillObject() {
Person person = new Person();
person.setName("John");
person.setAge(25);
person.setGender("male");
}
改为:
private static final int PERSON_AGE = 25;
private static final String PERSON_NAME = "John";
private static final String PERSON_GENDER = "male";
public void fillObject() {
Person person = new Person();
person.setName(PERSON_NAME);
person.setAge(PERSON_AGE);
person.setGender(PERSON_GENDER);
}
这样,我们可以使用常量来避免在代码中使用魔术数字,从而避免checkstyle MagicNumber错误的出现。