有两个功能具有相同的结构,但细节不同。如何摆脱重复?

时间:2016-04-09 21:19:42

标签: java refactoring

所以,这是我的功能:

  private void sendLeft() {
    leftSendersIndexes = newLeftSendersIndexes;
    Agent rightRecepient;
    int rightRecepientIdx = 0;
    Agent leftSender;
    for (int i = 0; i < leftSendersIndexes.size(); i++) {
        rightRecepientIdx = leftSendersIndexes.get(i) + 1;
        rightRecepient = list.get(rightRecepientIdx);
        leftSender = list.get(rightRecepientIdx - 1);
        rightRecepient.setNewLeftMsg(leftSender.getLeftMsg());
        rightRecepient.setLeftMsg(0); // reset left messages
    }
}

private void sendRight() {
    rightSendersIndexes = newRightSendersIndexes;
    Agent leftRecepient;
    int leftRecepientIdx = 0;
    Agent rightSender;
    for (int i = 0; i < rightSendersIndexes.size(); i++) {
        leftRecepientIdx = rightSendersIndexes.get(i) - 1;
        leftRecepient = list.get(leftRecepientIdx);
        rightSender = list.get(leftRecepientIdx + 1);
        leftRecepient.setNewRightMsg(rightSender.getRightMsg());
    }
}

他们非常相似。问题是,在第一个函数中,我有leftRecepientIdx+1,然后是leftRecepientIdx-1,我在第二个函数中有leftRecepientIdx-1leftRecepientIdx+1。我可以在一个中组合两个函数并添加一个布尔参数。但有没有更好的方法摆脱重复?

2 个答案:

答案 0 :(得分:1)

这样做的一种方法是进行重构:

private void sendLeft() {
    leftSendersIndexes = newLeftSendersIndexes;
    send(leftSendersIndexes, -1);
}

private void sendRight() {
    rightSendersIndexes = newRightSendersIndexes;
    send(rightSendersIndexes, +1);
}

private void send(List<Integer> indexes, int direction) {
    for (int i = 0; i < indexes.size(); i++) {
        int recipientIdx = indexes.get(i) - direction;
        Agent recipient = list.get(recipientIdx);
        Agent sender = list.get(recipientIdx + direction);
        if (direction == -1) {
            recipient.setNewLeftMsg(sender.getLeftMsg());
            recipient.setLeftMsg(0); // reset left messages
        }
        else {
            recipient.setNewRightMsg(sender.getRightMsg());
        }
    }
}

send方法根据direction参数封装逻辑:右为+1,左为-1。

答案 1 :(得分:0)

这些出现的顺序很重要,我建议合并,但是,我不知道那会做什么。将它们分开,如果这是借来的,这是故意制作的。