javaunit-testingconstantsgetter-setterbusiness-rules

Why will my getter and setter with a constant not work with string.length()?


Is anyone able to explain why when I use a constant within my if statement for String.length() it will not pass a valid test but if I hard code the values within the if statement it will pass?

public void setName(String name) {
    if (name.length() >= 1 && name.length() <= 20) {
        this.name = name;
    } else {
        throw new IllegalArgumentException();
    }
}

So the above will work but I thought it would be a better idea to create two constants UPPER_NAME_LIMIT and LOWER_NAME_LIMIT with the same values 1 and 20.

 * @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();
    }
}

The constants where coded as below

public static final int UPPER_NAME_LIMIT = 1;
public static final int LOWER_NAME_LIMIT = 20;

Solution

  • public static final int UPPER_NAME_LIMIT = 1;
    public static final int LOWER_NAME_LIMIT = 20;
    

    change it to

    public static final int UPPER_NAME_LIMIT = 20;
    public static final int LOWER_NAME_LIMIT = 1;