降低代码的复杂性

时间:2016-06-24 05:36:36

标签: java sonarlint

我使用下面的代码并使用两个continue语句,具体取决于某些逻辑但声纳列表显示此问题Reduce the total number of break and continue statements in this loop to use at most one.

如何解决此问题?

for (HashMap<String, String> objRequestIdVO : pObjTicketId) {
    List<TicketDetailsDO> objTicketDetailslist = storeManagerDao.getTicketDetailsWithTicketId(objRequestIdVO.get("requestId"));
    if (null == objTicketDetailslist || objTicketDetailslist.isEmpty()) {
        continue;
    }

    Integer iDesiredDsicount = objTicketDetailslist.get(0).getDesiredDiscount();
    String iSubDept = objTicketDetailslist.get(0).getSubdeptTicket().getSubDeptId();
    List<MCouponDO> objMCounponList = storeManagerDao.getMcouponData(iDesiredDsicount, iSubDept);

    if (null == objMCounponList || objMCounponList.isEmpty()) {
        continue;
    }

    String strHeader = objMCounponList.get(0).getHeader();
    objHeaderVO = new HeaderVO();
    objHeaderVO.setHeader(strHeader);
    objHeaderVO.setRequestId(objRequestIdVO.get("requestId"));
    objHeaderVOList.add(objHeaderVO);
}

3 个答案:

答案 0 :(得分:3)

更改空检查继续,不进行空检查并继续。只有在非空检查通过时才会执行代码,这与在null时说“continue”相同。

for (HashMap<String, String> objRequestIdVO : pObjTicketId) {
    List<TicketDetailsDO> objTicketDetailslist = storeManagerDao.getTicketDetailsWithTicketId(objRequestIdVO.get("requestId"));
    if (!(null == objTicketDetailslist || objTicketDetailslist.isEmpty())) {
        Integer iDesiredDsicount = objTicketDetailslist.get(0).getDesiredDiscount();
        String iSubDept = objTicketDetailslist.get(0).getSubdeptTicket().getSubDeptId();
        List<MCouponDO> objMCounponList = storeManagerDao.getMcouponData(iDesiredDsicount, iSubDept);
        if (!(null == objMCounponList || objMCounponList.isEmpty()) {
            String strHeader = objMCounponList.get(0).getHeader();
            objHeaderVO = new HeaderVO();
            objHeaderVO.setHeader(strHeader);
            objHeaderVO.setRequestId(objRequestIdVO.get("requestId"));
            objHeaderVOList.add(objHeaderVO);
        }
    }
}

答案 1 :(得分:1)

您可以使用流替换继续使用过滤器。

{{1}}

答案 2 :(得分:0)

如果调用-storeManagerDao.getTicketDetailsWithTicketId(objRequestIdVO.get("requestId"))storeManagerDao.getMcouponData(iDesiredDsicount, iSubDept)与进行DB调用有关,则比解决Sonar警告更大的问题。这是一个很大的性能点,应该-永远不要进行DB调用从循环内来看,这比多个继续和中断语句要危险得多

因此,我将首先重组您的DAO调用-storeManagerDao.getTicketDetailsWithTicketId,在您的主循环外一口气运行IN的SQL查询一堆objRequestIdVO.get("requestId")并生成一个{{1} } ...将自动删除您的第一个Map<String,List<TicketDetailsDO>>

接下来,您将通过迭代先前的映射if来重复构建Map<String,List<MCouponDO> objMCounponList>的相同过程,该映射的键类似于-Map<String,List<TicketDetailsDO>>

这样,您将有两个断开的循环,并且只有两个DB调用,并且您的Sonar警告会在此途中自动得到解决。