编程技巧

238 阅读1分钟

如何避免重复代码之Map结构初始化

# 修改代码前
public Map<Byte, List<String>> getSupplierAreaCodeMap() {
        // 代码重复的map要如何精简初始化赋值呐?
        supplierAreaCodeMap = new HashMap<>(8);
        if (CollectionUtils.isEmpty(citySupplierConfigVoList)) {
            return null;
        }
        
        for (CitySupplierConfigVO configVO : citySupplierConfigVoList) {
            Byte supplier = configVO.getSupplier();
            if (supplierAreaCodeMap.get(supplier) != null) {
                List<String> areaCodeList = supplierAreaCodeMap.get(supplier);
                areaCodeList.add(configVO.getAreaCode());
                supplierAreaCodeMap.put(supplier,areaCodeList);
            } else {
                List<String> areaCodeList = new ArrayList<>();
                areaCodeList.add(configVO.getAreaCode());
                supplierAreaCodeMap.put(supplier,areaCodeList);
            }
        }
    return supplierAreaCodeMap;
}
    
# 修改步骤
/* 1.先把公共部分areaCodeList.add(configVO.getAreaCode());
   和supplierAreaCodeMap.put(supplier,areaCodeList);提取出来*/
/* 2.然后针对不同的部分进行简化,采用快速错误的方法,过滤不满足的条件
   在这里就是判断value值是否为空*/
/* 3.if (supplierAreaCodeMap.get(supplier) == null) {
        supplierAreaCodeMap.put(supplier,new ArrayList());
     }
<!--这时执行过这部分代码后,一定是value有值的部分,所以紧接着第1部和第二步即可-->*/

# 修改代码后
public Map<Byte, List<String>> getSupplierAreaCodeMap() {
        // 代码重复的map要如何精简初始化赋值呐?
        supplierAreaCodeMap = new HashMap<>(8);
        if (CollectionUtils.isEmpty(citySupplierConfigVoList)) {
            return null;
        }
        // 合理的利用引用变量的属性,来修改引用变量对应的值使代码更加简洁
        for (CitySupplierConfigVO configVO : citySupplierConfigVoList) {
            Byte supplier = configVO.getSupplier();
            if (supplierAreaCodeMap.get(supplier) == null) {
                supplierAreaCodeMap.put(supplier,new ArrayList<String>());
            }
            supplierAreaCodeMap.get(supplier).add(configVO.getAreaCode());
        }
    return supplierAreaCodeMap;
}

# 效果9行变4行