任何人都可以想出一种重构方法来避免重复代码吗?

时间:2012-05-01 07:28:36

标签: java search refactoring

我有两个搜索循环来执行不同的操作,但我对这看起来多么重复感到不满。

用于删除项目的第一种方法如下:

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.");    
    }
}

我该怎么重构呢?

3 个答案:

答案 0 :(得分:3)

返回播放器索引i的方法“FindPlayer”怎么样?然后,RemovePlayer和RetrievePlayer就是:

public void RemovePlayer(int theID){
    int playerId = FindPlayer(theID);
    if (playerId >= 0) {
        playerObjects.remove(playerId);
    }
}

public void RetrievePlayer(int theID){
    int playerId = FindPlayer(theID);
    if (playerId >= 0) {
        Person player = (Person) playerObjects.get(playerId);
        player.getDetails();
    }
}

“FindPlayer”方法有点像这样:

protected int FindPlayer(int theID){
    if (playerObjects.size() != 0){
        for (int i = 0; i < playerObjects.size(); i++){
            Person player = (Person) playerObjects.get(i);
            if (player.getID() == theID){
                return i;
            }
        }

        System.out.println("Player with ID # " + theID + " not found");
    } else {
        System.out.println("No players have been added.");    
    }

    return -1;
}

答案 1 :(得分:1)

将玩家置于Map<Integer,Player>。然后使用Map的基本方法(putremove)而不是循环遍历列表。

答案 2 :(得分:0)

如果您再拆分,则可以使用find方法返回以玩家为参数的Playerremove方法。我更喜欢这个而不是返回索引,因为索引可能是临时的(例如,如果其他人添加到列表中,索引可能会失效)。

你可以做的更多(可能是带有谓词的findAllfilter方法),但在你有理由这样做之前我不会看这些(你不是需要它)