Refactor code primitive

This commit is contained in:
abdelrahmanassem 2024-12-27 12:58:37 +02:00
parent 655f9cc5fc
commit df3aee345d
2 changed files with 24 additions and 23 deletions

View file

@ -113,35 +113,15 @@ public class Owner extends Person {
* @param id to test * @param id to test
* @return the Pet with the given id, or null if no such Pet exists for this Owner * @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()) { for (Pet pet : getPets()) {
if (!pet.isNew()) { if (identifier.matches(pet) && (!ignoreNew || !pet.isNew())) {
Integer compId = pet.getId();
if (compId.equals(id)) {
return pet; return pet;
} }
} }
}
return null; 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 @Override
public String toString() { public String toString() {

View file

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