以下是对代码的优化建议:

  1. 在方法签名中,将返回类型从Result<Object>更改为Result<?>。这样可以使方法更通用,不限制返回类型为Object。

  2. 将请求参数Map<String, Object> params更改为具体的请求对象,例如UpdateSpecificRegularRequest。这样可以明确指定请求参数的结构,提高代码的可读性。

  3. 将获取权限验证token的代码提取为一个方法,以提高代码的可重用性。例如:

private String getAdminToken(HttpServletRequest request) {
    String token = (String) request.getAttribute("claims_admin");
    if (token == null || "".equals(token)) {
        throw new RuntimeException("权限不足!");
    }
    return token;
}

然后在updateSpecificRegulars方法中调用该方法来获取token。

  1. 将获取手机号和验证码的代码提取为方法,以提高代码的可重用性。例如:
private String getPhone(Map<String, Object> params) {
    String phone = (String) params.get("phone");//手机号
    if (!StringUtils.hasText(phone)) {
        log.error("phone为空!");
        throw new RuntimeException("phone为空!");
    }
    return phone;
}

private String getUserCode(Map<String, Object> params) {
    String userCode = (String) params.get("code");//验证码
    if (!StringUtils.hasText(userCode)) {
        log.error("userCode为空!");
        throw new RuntimeException("userCode为空!");
    }
    return userCode;
}

然后在updateSpecificRegulars方法中调用这两个方法来获取手机号和验证码。

  1. 使用JSONObject.parseArray方法直接将jsonArray转换为List<SpecificRegular>,而不需要先将其转换为String再转换为List<SpecificRegular>。例如:
List<SpecificRegular> specificRegulars = jsonObject.getJSONArray("specificRegular").toJavaList(SpecificRegular.class);
  1. 在遍历specificRegulars集合时,可以使用Java 8的流式操作和Lambda表达式来简化代码。例如:
List<SpecificRegular> specificRegularList = specificRegulars.stream()
    .map(specificRegular -> {
        SpecificRegular specificRegularMy = specificRegularService.queryOneSpecificRegularByID(specificRegular.getSpecificRegularId());
        if (specificRegularMy == null) {
            log.error("通过具体规则id找到具体规则为空");
            throw new RuntimeException("通过具体规则id找到具体规则为空");
        }
        if (StringUtils.hasText(specificRegular.getVoiceBroadcastText()) && specificRegular.getDemeritState() != 0) {
            // ...
        } else if (StringUtils.hasText(specificRegular.getVoiceBroadcastText()) && specificRegular.getDemeritState() == 0) {
            // ...
        } else if (!StringUtils.hasText(specificRegular.getVoiceBroadcastText()) && specificRegular.getDemeritState() == 0) {
            // ...
        }
        return specificRegularMy;
    })
    .collect(Collectors.toList());
  1. 使用specificRegularList.isEmpty()替换CollectionUtils.isEmpty(specificRegularList),以减少对第三方库的依赖。

  2. 在批量更新数据库之前,可以先判断specificRegularList是否为空,如果为空则直接返回失败结果。例如:

if (specificRegularList.isEmpty()) {
    log.error("前端传回集合为空");
    return new Result<>(ResultCode.FAIL);
}

这些优化建议可以提升代码的可读性和可维护性,并且可能会稍微提升代码的执行速度。请根据实际情况选择适合的优化方式

PostMappingupdateSpecificRegulars public ResultObject updateSpecificRegularsRequestBody MapString Object params HttpServletRequest request 权限验证 String token = String requestgetAttrib

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

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