天天看點

Java代碼提高可讀性的一點小體會

優化前的代碼:

/**
     * 是否屬于生鮮商品
     * 基礎 轉标 組合 三種商品的子商品的機關都得是 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語句,以後絕對不能再出現在,我寫的代碼中。

繼續閱讀