有人能够解释为什么当我在String.length()的if语句中使用常量时,它不会通过有效的测试,但是如果我对if语句中的值进行硬编码,它将通过吗?
public void setName(String name) {
if (name.length() >= 1 && name.length() <= 20) {
this.name = name;
} else {
throw new IllegalArgumentException();
}
}
所以上面的方法可以工作,但我认为最好用两个相同的值1和20创建两个常量UPPER_NAME_LIMIT和LOWER_NAME_LIMIT。
* @param name the name to set
*/
public void setName(String name) {
if (name.length() >= LOWER_NAME_LIMIT && name.length() <= UPPER_NAME_LIMIT) {
this.name = name;
} else {
throw new IllegalArgumentException();
}
}
常量编码如下
public static final int UPPER_NAME_LIMIT = 1;
public static final int LOWER_NAME_LIMIT = 20;
public static final int UPPER_NAME_LIMIT = 1;
public static final int LOWER_NAME_LIMIT = 20;
将其更改为
public static final int UPPER_NAME_LIMIT = 20;
public static final int LOWER_NAME_LIMIT = 1;