优化建议:

  1. 使用早期退出的方式,将判断条件为false的情况提前,减少嵌套层数。

  2. 将重复的代码提取为方法,避免冗余代码。

  3. 将多个if条件判断语句合并为一个,提高代码可读性。

  4. 将局部变量提前声明,增加代码可读性。

  5. 增加注释,方便他人理解代码逻辑。

优化后的代码如下所示:

// 参数校验 if (StringUtils.isBlank(param.getKey())) { throw new YshopException("参数不能为空"); }

// 获取旧订单详情 String batchIdKey = redisUtils.getY(PAY_TMPLID + param.getKey()); List oldOrderDetailList = findDetailById(batchIdKey);

// 判断旧订单是否存在 if (CollectionUtil.isNotEmpty(oldOrderDetailList)) { OrdersDetail ordersDetail = oldOrderDetailList.get(0); Integer payStatus = ordersDetail.getPayStatus(); Integer status = ordersDetail.getStatus();

// 校验当前订单是否支付
if (YxOrderEnum.PAY_STATUS1.getStatus().equals(payStatus)) {
    throw new YshopException("订单已支付");
}

// 只有未支付、关闭订单才可以在原有订单继续支付
if (!status.equals(YxOrderEnum.status0.getStatus()) && !status.equals(YxOrderEnum.status50.getStatus())) {
    oldOrderDetailList = null;
}

}

// 处理商品库存 List productStockList = new ArrayList<>(); Map<Integer, YxOrderAndItemIdDto> idMap = new HashMap<>();

// 第一次支付或者重复支付key过期 if (CollectionUtil.isEmpty(oldOrderDetailList)) { for (YxOrderProductDto yxOrderProductDto : param.getOrderProductList()) { if (yxOrderProductDto.getQuantity() > 0) { productStockList.add(yxOrderProductDto); } } } else { // 订单未支付处理,重复支付时修改了商品数量 for (OrdersDetail ordersDetail : oldOrderDetailList) { YxOrderItem yxOrderItem = ordersDetail.getOrderItem(); // 旧订单商品对应的订单id和订单itemId idMap.put(yxOrderItem.getProductId(), new YxOrderAndItemIdDto(ordersDetail.getId(), yxOrderItem.getId(), yxOrderItem.getBatchId()));

    // 原来订单item的商品和传参的商品数量进行比较
    for (YxOrderProductDto yxOrderProductDto : param.getOrderProductList()) {
        if (yxOrderItem.getProductId().equals(yxOrderProductDto.getProductId())) {
            int quantity = yxOrderProductDto.getQuantity() - yxOrderItem.getProductQuantity();
            // 商品修改数量的则进行库存扣减
            if (quantity != 0) {
                YxOrderProductDto orderProduct = new YxOrderProductDto();
                orderProduct.setProductId(yxOrderItem.getProductId());
                orderProduct.setSkuId(yxOrderItem.getProductSkuId());
                orderProduct.setQuantity(quantity);
                productStockList.add(orderProduct);
            }
            break;
        }
    }
}
优化以下代码 if StringUtilsisNotBlankparamgetKey String batchIdKey = redisUtilsgetYPAY_TMPLID + paramgetKey; oldOrderDetailList = findDetailByIdbatchIdKey; if CollectionUti

原文地址: https://www.cveoy.top/t/topic/f5xu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录