boolean validateName(String name, boolean throwException) {
// no name can be less than two characters
if (name == null || name.length() < 2) {
if (throwException) {
throw new IllegalArgumentException("The name is too short, it must be at least two characters");
}
return false;
}
// a name can only contain letters, spaces and hyphens
for (int i = 0; i < name.length(); i++) {
char c = name.charAt(i);
if (! (Character.isLetter(c) || c == ' ' || c == '-')) {
if (throwException) {
throw new IllegalArgumentException("'" + c + "' is an illegal character, a name can only contain letters, space or hyphens");
}
return false;
}
return true;
}
void setName(String name) {
validateName(name, true);
this.name = name;
} |