例子1:原文:https://blog.csdn.net/csh_275308734/article/details/82150983
if(a == 1) {
if (b == 2) {
//逻辑
}
}
可以改为:if(a == 1 && b == 2) {
//逻辑
}
例子2:
if(a==1) {
if(b==1) {
//逻辑2
if(c==1) {
//逻辑3
}
}
//逻辑1
}
可以改为:if(a ==1 ) {
//逻辑1
}
if(b == 2) {
//逻辑2
}
if(c == 3) {
//逻辑3
}
例子3:
if(a==1) {
b=1;
} else {
b=2;
}
可以改为三元运算符:b = a == 1 ? 1 : 2;
例子4:
private boolean judge(){
if(a==1 && b==1){
return true;
} else {
return false;
}
}
直接return就行了:private boolean judge() {
return a==1 && b==1;
}
避免参数赋值
public Date getStartTime(Date date) {
date.setMinutes(fromMinute);
date.setDate(fromHour);
date.setDate(fromHour);
date.setSeconds(0);
return date;
}
重构后public Date getStartTime(final Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, fromHour);
calendar.set(Calendar.MINUTE, fromMinute);
calendar.set(Calendar.SECOND, 0);
return calendar.getTime();
}
枚举类重构
if (BusinessCategoryEnum.PRODUCT.getCode().equals(businessCategory)){
Iterator<BusRelationVO> it = busRelationVOList.iterator();
while(it.hasNext()){
BusRelationVO vo = it.next();
if (!BusinessCategoryEnum.PRODUCT.getDescription().equals(vo.getBusinessCategoryName())){
it.remove();
}
}
}else if (BusinessCategoryEnum.PROJECT.getCode().equals(businessCategory)){
Iterator<BusRelationVO> it = busRelationVOList.iterator();
while(it.hasNext()){
BusRelationVO vo = it.next();
if (!BusinessCategoryEnum.PROJECT.getDescription().equals(vo.getBusinessCategoryName())){
it.remove();
}
}
}else if (BusinessCategoryEnum.SELL.getCode().equals(businessCategory)){
Iterator<BusRelationVO> it = busRelationVOList.iterator();
while(it.hasNext()){
BusRelationVO vo = it.next();
if (!BusinessCategoryEnum.SELL.getDescription().equals(vo.getBusinessCategoryName())){
it.remove();
}
}
}
重构后
if (BusinessCategoryEnum.PRODUCT.getCode().equals(businessCategory)){
remove(busRelationVOList, BusinessCategoryEnum.PRODUCT);
}else if (BusinessCategoryEnum.PROJECT.getCode().equals(businessCategory)){
remove(busRelationVOList, BusinessCategoryEnum.PROJECT);
}else if (BusinessCategoryEnum.SELL.getCode().equals(businessCategory)){
remove(busRelationVOList, BusinessCategoryEnum.SELL);
}
/**
* 按照大类 分开
*/
private void remove(List<BusRelationVO> busRelationVOList, BusinessCategoryEnum categoryEnum) {
Iterator<BusRelationVO> it = busRelationVOList.iterator();
while (it.hasNext()) {
BusRelationVO vo = it.next();
if (!categoryEnum.getDescription().equals(vo.getBusinessCategoryName())) {
it.remove();
}
}
}