优化这段代码: public RespResult<String> mod(UserQo userQo, ContactQo contactQo) { List<User> users = userMapper.selectByCustomNumber(userQo.getCustomNumber()); if (ObjectUtils.isEmpty(users)) { int count = userMapper.updateUser(userQo); if (count > 0 && userQo.getStatus() == status_not_del) { contactQo.setCustomId(userQo.getCustomId()); count = contactMapper.updateContact(contactQo); if (count > 0) { AdminOperate adminOperate = new AdminOperate(); adminOperate.setContent(updateCustom); count = adminOperateMapper.insert(adminOperate); if (count > 0) { return RespResult.success("success"); } else { throw new ServiceException(ResultCode.USER_UPDATE_EXIST); } } else { throw new ServiceException(ResultCode.USER_UPDATE_ERROR); } } else { int count01 = contactMapper.updateUserStatus(userQo.getCustomId()); if (count01 > 0) { return RespResult.success("已删除用户联系方式"); } else { throw new ServiceException(ResultCode.USER_UPDATE_EXIST); } } }else { throw new ServiceException(ResultCode.USER_EXIST); } }
时间: 2024-02-10 18:35:24 浏览: 70
public RespResult<String> mod(UserQo userQo, ContactQo contactQo) {
List<User> users = userMapper.selectByCustomNumber(userQo.getCustomNumber());
if (!users.isEmpty()) {
throw new ServiceException(ResultCode.USER_EXIST);
}
int count = userMapper.updateUser(userQo);
if (count <= 0 || userQo.getStatus() != status_not_del) {
int count01 = contactMapper.updateUserStatus(userQo.getCustomId());
if (count01 <= 0) {
throw new ServiceException(ResultCode.USER_UPDATE_EXIST);
}
return RespResult.success("已删除用户联系方式");
}
contactQo.setCustomId(userQo.getCustomId());
count = contactMapper.updateContact(contactQo);
if (count <= 0) {
throw new ServiceException(ResultCode.USER_UPDATE_ERROR);
}
AdminOperate adminOperate = new AdminOperate();
adminOperate.setContent(updateCustom);
count = adminOperateMapper.insert(adminOperate);
if (count <= 0) {
throw new ServiceException(ResultCode.USER_UPDATE_EXIST);
}
return RespResult.success("success");
}
优化如下:
1. 如果用户已经存在,直接抛出异常,避免多余的嵌套和判断。
2. 合并原来的 if 判断,减少嵌套和冗余判断。
3. 将抛出异常的部分提前处理,避免多余的数据库操作。
4. 将成功的返回值统一处理,避免多处重复写返回值。
5. 优化变量名,提高代码可读性。
阅读全文