Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
String validateName(String name) {
	// no name can be less than two characters
	if (name.length < 2) {
		return "The name is too short, it must be at least two characters";
	}
	// 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 == '-')) {
			return "'" + c + "' is an illegal character, a name can only contain letters, space or hyphens";
		}
	}
}

void setName(String name) {
	String message = validateName(name);
	if (message != null) {
		throw new IllegalArgumentException(message);
	}
	this.name = name;
}

Kode som kaller valideringsmetoden må huske meldingen, siden den skal brukes hvis den ikke er null.

Code Block
boolean isValidNamevalidateName(String name, boolean throwException) {
	// no name can be less than two characters
	if (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) {
	isValidNamevalidateName(name, true);
	this.name = name;
}

Setteren blir enkel, og koden utenfor klassen som ikke ønsker at unntak skal utløses, kaller valideringsmetoden med false som andre argument.