优化这段Java代码:if (("S".equals(dept) && "Y".equals(bagInfo.getBagSOpen()) && !"Y".equals(bagInfo.getBagSFinished())) || ("C".equals(dept) && "Y".equals(bagInfo.getBagCOpen()) && !"Y".equals(bagInfo.getBagCFinished())) || ("C".equals(dept) && "Y".equals(bagInfo.getBagGOpen()) && !"Y".equals(bagInfo.getBagGFinished()))) { record.setBagState("0"); record.setBagDescribe("需开包"); } else if (("S".equals(dept) && "Y".equals(bagInfo.getBagSOpen()) && "Y".equals(bagInfo.getBagSFinished())) || ("C".equals(dept) && "Y".equals(bagInfo.getBagCOpen()) && "Y".equals(bagInfo.getBagCFinished())) || ("C".equals(dept) && "Y".equals(bagInfo.getBagGOpen()) && "Y".equals(bagInfo.getBagGFinished()))) { record.setBagState("0"); record.setBagDescribe("开包完成"); } else if ((("S".equals(dept) && "N".equals(bagInfo.getBagSOpen()) && "N".equals(bagInfo.getBagSFinished())) || ("C".equals(dept) && "N".equals(bagInfo.getBagCOpen()) && "N".equals(bagInfo.getBagCFinished())) || ("C".equals(dept) && "N".equals(bagInfo.getBagGOpen()) && "N".equals(bagInfo.getBagGFinished())))) { record.setBagState("0"); record.setBagDescribe("正常"); } else { record.setBagState("0"); record.setBagDescribe("未知"); }
时间: 2023-12-17 15:05:55 浏览: 181
详解Java代码常见优化方案
可以将多个if-else语句合并为一个switch-case语句,将相同的代码提取出来,减少代码重复:
```
switch (dept) {
case "S":
if ("Y".equals(bagInfo.getBagSOpen())) {
if ("Y".equals(bagInfo.getBagSFinished())) {
setBagState(record, "0", "开包完成");
} else {
setBagState(record, "0", "需开包");
}
} else if ("N".equals(bagInfo.getBagSOpen()) && "N".equals(bagInfo.getBagSFinished())) {
setBagState(record, "0", "正常");
} else {
setBagState(record, "0", "未知");
}
break;
case "C":
if ("Y".equals(bagInfo.getBagCOpen())) {
if ("Y".equals(bagInfo.getBagCFinished())) {
setBagState(record, "0", "开包完成");
} else {
setBagState(record, "0", "需开包");
}
} else if ("Y".equals(bagInfo.getBagGOpen())) {
if ("Y".equals(bagInfo.getBagGFinished())) {
setBagState(record, "0", "开包完成");
} else {
setBagState(record, "0", "需开包");
}
} else if ("N".equals(bagInfo.getBagCOpen()) && "N".equals(bagInfo.getBagCFinished())) {
setBagState(record, "0", "正常");
} else if ("N".equals(bagInfo.getBagGOpen()) && "N".equals(bagInfo.getBagGFinished())) {
setBagState(record, "0", "正常");
} else {
setBagState(record, "0", "未知");
}
break;
default:
setBagState(record, "0", "未知");
break;
}
private void setBagState(Record record, String state, String describe) {
record.setBagState(state);
record.setBagDescribe(describe);
}
```
阅读全文