異なる操作を実行するための 2 つの検索ループがありますが、これがいかに反復的であるかに不満があります。
アイテムを削除するために使用される最初の方法は次のとおりです。
public void RemovePlayer(int theID){
boolean matchFound = false;
if (playerObjects.size() != 0){
for (int i = 0; i < playerObjects.size(); i++){
Person playerToRemove = (Person) playerObjects.get(i);
if (playerToRemove.getID() == theID){
playerObjects.remove(i);
System.out.println("Player with ID # " + theID + " removed");
matchFound = true;
// As ID is unique, once a player is found it is unnecessary to continue looping
break;
}
// If matchFound is never set to true then show appropriate error
if (matchFound == false) {
System.out.println("Player with ID # " + theID + " not found");
}
}
}
else {
System.out.println("No players have been added.");
}
}
2 番目のメソッドは、基本的に同じコードですが、一致が見つかった場合に別のアクションを実行します。
public void RetrievePlayer(int theID){
boolean matchFound = false;
if (playerObjects.size() != 0){
for (int i = 0; i < playerObjects.size(); i++){
Person playerToRetrieve = (Person) playerObjects.get(i);
if (playerToRetrieve.getID() == theID){
System.out.println("PLAYER FOUND:");
playerToRetrieve.GetDetails();
matchFound = true;
break;
}
// If matchFound is never set to true then show appropriate error
if (matchFound == false) {
System.out.println("Player with ID # " + theID + " not found");
}
}
} else {
System.out.println("No players have been added.");
}
}
これをリファクタリングするにはどうすればよいですか?