所以,这是我的功能:

  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。我可能将两个函数合而为一,并添加一个布尔参数。但是,有没有更好的方法来消除重复呢?

最佳答案

一种实现方法是使用此重构:

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表示左。

08-15 19:31