优化前的代码:
/**
* 是否属于生鲜商品
* 基础 转标 组合 三种商品的子商品的单位都得是 KG 或者 斤
* @param itemList
* @return
*/
private Boolean isFresh(List<ReqProductCombinedItemVO> itemList) {
if (CollUtil.isEmpty(itemList)) {
return false;
}
for (ReqProductCombinedItemVO item : itemList) {
if (item.getSapProductUnit() == null || !(item.getSapProductUnit().contains("KG") || item.getSapProductUnit().contains("斤"))) {
return false;
}
}
return true;
}
优化后的代码:
/**
* 是否属于生鲜商品
* 基础 转标 组合 三种商品的子商品的单位都得是 KG 或者 斤
* @param itemList
* @return
*/
private Boolean isFresh(List<ReqProductCombinedItemVO> itemList) {
//集合本身为空
if (CollUtil.isEmpty(itemList)) {
return false;
}
for (ReqProductCombinedItemVO item : itemList) {
//测试环境的垃圾数据很多,集合中的元素也很有可能为空,如果不校验,下面的调用get方法就会报NPE
if (item == null) {
return false;
}
String sapProductUnit = item.getSapProductUnit();
//get出来的属性有可能性为空,用isBlank方法判断,把像白板这样的无意义的值也过滤掉
if(StrUtil.isBlank(sapProductUnit)){
return false;
}
//if语句过长时,为了保证可读性,需要对if语句进行分拆
//一直比较讨厌Java中的感叹号 取反运算符,可读性很差,所以我把取反又封装了一层,保证可读性
Boolean notKg = StrTools.isNotContains(sapProductUnit,"KG");
Boolean notJin = StrTools.isNotContains(sapProductUnit,"斤");
if(notKg && notJin){
return false;
}
}
return true;
}
package com.yonghui.yh.soi.manage.productcenter.common.utils;
import org.apache.commons.lang3.StringUtils;
/**
* @Description: SOI项目中好几个StringUtils类,为了防止重名,引很长的包路径,单独写一个类,继承apache commons包下的StringUtils类
* @Author: lihg
* @Date: 2019-08-30
*/
public class StrTools extends StringUtils {
/**
* 不包含 某些字符
* @param str 源字符
* @param searchChar 待搜索字符
* @return
*/
public static Boolean isNotContains(String str,String searchChar){
return !contains(str,searchChar);
}
}
现在我看到不顺眼的代码,一言不合就优化,哈哈、
结合看的一些文档,确实需要对if语句,进行可读性优化,
又臭又长的if语句,以后绝对不能再出现在,我写的代码中。