JAVA重构方法

时间:2017-05-11 11:45:18

标签: java refactoring crud mapper

我有一个名为Travel的实体,它有成本中心列表我已经为成本中心处理CRUD操作创建了一个代码

protected void assignCostCenter(CostCenterDTO costCenterDTO, Travel travel, Long detailsId) throws BusinessException {
    CostCenter costCenter = null;
    if (costCenterDTO.getCostCenters() != null) {
        Center center = commonDao.find(costCenterDTO.getCostCenters().getId());
        costCenter = costCenterDTOMapper.mapToDTO(costCenterDTO.getCostCenters(), travel, detailsId, center);
        if (costCenter != null && !travel.getCostCenters().contains(costCenter)) {
            travel.getCostCenters().add(costCenter);
        }
    } else {
        travel.setCostCenters(travel.getCostCenters().stream().filter(costCenter1 -> !(costCenter1.getDetailId().equals(detailsId))).collect(Collectors.toList()));
    }
}

在mapper中

 public CostCenter mapToCostCenter(CostCenterDTO costCenterDTO, Travel travel, Long claimDetail, Center center) throws BusinessException {
        CostCenter costCenter = new CostCenter();
        CostCenter costCenterToUpdate = travel.getCostCenters()
                .stream()
                .filter(costCenter1 -> costCenter1.getDetailId().equals(claimDetail))
                .findFirst()
                .orElse(null);
        if (costCenterToUpdate == null) {
            costCenter.setCenter(center);
            costCenter.setTravel(travel);
            costCenter.setDetailId(claimDetail);
        } else {
            costCenterToUpdate.setCenter(center);
            return costCenterToUpdate;
        }
        return costCenter;
    }

功能是,如果分配了新的CostCenter,我从db中获取中心并分配给mapper中的mapper,我调用travel.getCostCenters来查看是否已经分配了具有相同详细ID的costCenter,如果我刚更新的话如果没有我创建新并返回,并添加到列表如果不存在,也如果CostCenterDTO为null然后我从详细IDId列表costCenter中删除,但我的问题是如何重构它,因为它不看起来整洁?

1 个答案:

答案 0 :(得分:0)

我在这里看到的关于可读性的一件事:违反SLA原则。

含义:真的有助于在ifs中没有ifs。相反,你编写小辅助方法来做这样的工作;这样每个方法只包含"相同"的元素。抽象层。

除此之外;在风格层面:我更喜欢到"返回" over" else&#34 ;;像:

 if (costCenterToUpdate == null) {
   return updateCostCenter(center, travel, claimDetail);   
 }

 costCenterToUpdate.setCenter(center);
 return costCenterToUpdate;