优化以下代码: StringBuilder describe = new StringBuilder(); if (deleteName.length() > 0) { deleteName.deleteCharAt(deleteName.length() - 1); describe.append(String.format(SalaryTypeConstant.DELETE_FIXED_SALARY_FIELD, deleteName)).append(","); } if (updateName.length() > 0) { updateName.deleteCharAt(updateName.length() - 1); describe.append(String.format(SalaryTypeConstant.UPDATE_FIXED_SALARY_FIELD, updateName)).append(","); } if (addName.length() > 0) { addName.deleteCharAt(addName.length() - 1); describe.append(String.format(SalaryTypeConstant.ADD_FIXED_SALARY_FIELD, addName)).append(","); } if (describe.length() > 0) { describe.deleteCharAt(describe.length() - 1); }
时间: 2024-04-11 12:27:22 浏览: 79
以下是对代码进行优化的建议:
```java
StringBuilder describe = new StringBuilder();
if (deleteName.length() > 0) {
describe.append(String.format(SalaryTypeConstant.DELETE_FIXED_SALARY_FIELD, deleteName.deleteCharAt(deleteName.length() - 1)));
describe.append(",");
}
if (updateName.length() > 0) {
describe.append(String.format(SalaryTypeConstant.UPDATE_FIXED_SALARY_FIELD, updateName.deleteCharAt(updateName.length() - 1)));
describe.append(",");
}
if (addName.length() > 0) {
describe.append(String.format(SalaryTypeConstant.ADD_FIXED_SALARY_FIELD, addName.deleteCharAt(addName.length() - 1)));
describe.append(",");
}
if (describe.length() > 0) {
describe.deleteCharAt(describe.length() - 1);
}
```
优化的主要改动是将 `deleteName.deleteCharAt(deleteName.length() - 1)` 直接放入 `String.format()` 方法中,避免了多余的操作。同时,将 `describe.append(",")` 的操作提前到 `if` 条件中,避免了不必要的判断和操作。
阅读全文