Consider the Animal class (provided).
Add a method isValidName(String name)
that returns false if the given name is null
or empty.
Revise the constructor and (name) setter
so that it calls that method
on each of its arguments
and throws an IllegalArgumentException
if the name is not valid.
Test your revisions on the following code:
Animal myPet;
try {
myPet = new Animal(Animal.DOG, "");
System.out.println("FAIL -- empty name");
} catch (IllegalArgumentException iae) {
System.out.println("OK -- empty name");
}
try {
myPet = new Animal(Animal.DOG, null);
System.out.println("FAIL -- null name");
} catch (IllegalArgumentException iae) {
System.out.println("OK -- null name");
}
try {
myPet = new Animal("", "Okie Dokie");
System.out.println("FAIL -- empty species");
} catch (IllegalArgumentException iae) {
System.out.println("OK -- empty species");
}
try {
myPet = new Animal(null, "Weird");
System.out.println("FAIL -- null species");
} catch (IllegalArgumentException iae) {
System.out.println("OK -- null species");
}
try {
myPet = new Animal("penguin", "Happy");
System.out.println("OK -- SO FAR!");
myPet.setName("");
System.out.println("FAIL -- empty new name");
} catch (IllegalArgumentException iae) {
System.out.println("OK -- empty new name");
}
try {
myPet = new Animal("penguin", "Happy");
System.out.println("OK -- SO FAR!");
myPet.setName(null);
System.out.println("FAIL -- null new name");
} catch (IllegalArgumentException iae) {
System.out.println("OK -- null new name");
}
You should,
of course,
see no FAIL messages at all.