gpt4 book ai didi

java - 有两个结构相同但细节不同的函数。如何摆脱重复?

转载 作者:行者123 更新时间:2023-11-30 10:46:30 24 4
gpt4 key购买 nike

所以,这是我的功能:

  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 在第二个函数中。我可以将两个函数合二为一并添加一个 boolean 参数。但是有没有更好的方法来消除重复?

最佳答案

一种方法是使用这种重构:

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 为左。

关于java - 有两个结构相同但细节不同的函数。如何摆脱重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36522843/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com