diff --git a/src/main/java/org/springframework/samples/petclinic/owner/Owner.java b/src/main/java/org/springframework/samples/petclinic/owner/Owner.java index 675b2140e..4fdf4bb44 100644 --- a/src/main/java/org/springframework/samples/petclinic/owner/Owner.java +++ b/src/main/java/org/springframework/samples/petclinic/owner/Owner.java @@ -113,35 +113,15 @@ public class Owner extends Person { * @param id to test * @return the Pet with the given id, or null if no such Pet exists for this Owner */ - public Pet getPet(Integer id) { + public Pet findPet(PetIdentifier identifier, boolean ignoreNew) { for (Pet pet : getPets()) { - if (!pet.isNew()) { - Integer compId = pet.getId(); - if (compId.equals(id)) { - return pet; - } + if (identifier.matches(pet) && (!ignoreNew || !pet.isNew())) { + return pet; } } return null; } - /** - * Return the Pet with the given name, or null if none found for this Owner. - * @param name to test - * @param ignoreNew whether to ignore new pets (pets that are not saved yet) - * @return the Pet with the given name, or null if no such Pet exists for this Owner - */ - public Pet getPet(String name, boolean ignoreNew) { - for (Pet pet : getPets()) { - String compName = pet.getName(); - if (compName != null && compName.equalsIgnoreCase(name)) { - if (!ignoreNew || !pet.isNew()) { - return pet; - } - } - } - return null; - } @Override public String toString() { diff --git a/src/main/java/org/springframework/samples/petclinic/owner/PetIdentifier.java b/src/main/java/org/springframework/samples/petclinic/owner/PetIdentifier.java new file mode 100644 index 000000000..0dfcde481 --- /dev/null +++ b/src/main/java/org/springframework/samples/petclinic/owner/PetIdentifier.java @@ -0,0 +1,21 @@ +public class PetIdentifier { + private final String name; + private final Integer id; + + public PetIdentifier(Integer id) { + this.id = id; + this.name = null; + } + + public PetIdentifier(String name) { + this.name = name; + this.id = null; + } + + public boolean matches(Pet pet) { + if (id != null) { + return pet.getId().equals(id); + } + return pet.getName().equalsIgnoreCase(name); + } +}