我有兩個搜索循環來執行不同的操作,但我對這看起來多麼重複感到不滿。任何人都可以想出一種方法來重構這個以避免重複的代碼?
用於刪除項目的第一種方法如下:
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.");
}
}
而第二個方法,該方法基本上是相同的碼,但是,如果發現匹配是如下執行不同的動作:
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.");
}
}
我該如何重構這個?
謝謝,這就是我的編程語言尖端的解決方案,可以這麼說! –