优化这段代码@Autowired private UserService userService; @RequestMapping("/addUser") public ReturnCodeUtil addUser(@RequestBody User user) { ReturnCodeUtil returnCodeUtil = new ReturnCodeUtil(); if(null == user.getUserFlag()){ returnCodeUtil.setResult(false); return returnCodeUtil; } int res = this.userService.addUser(user); if (res>0) { returnCodeUtil.setResult(true); } else { returnCodeUtil.setResult(false); } return returnCodeUtil; } @RequestMapping("/register") public ReturnCodeUtil register(@RequestBody User user) { ReturnCodeUtil returnCodeUtil = new ReturnCodeUtil(); if(user == null) { returnCodeUtil.setResult(false); return returnCodeUtil; } int res = this.userService.addUser(user); if(res>0){ returnCodeUtil.setResult(true); }else returnCodeUtil.setResult(false); return returnCodeUtil; }
时间: 2024-04-25 17:27:18 浏览: 55
mybatisplus常用控制类和分类查询查用代码
这段代码中存在重复的逻辑,可以将其优化为以下代码:
@Autowired
private UserService userService;
@RequestMapping("/addUser")
public ReturnCodeUtil addUser(@RequestBody User user) {
ReturnCodeUtil returnCodeUtil = new ReturnCodeUtil();
if (user.getUserFlag() == null || user == null) {
returnCodeUtil.setResult(false);
return returnCodeUtil;
}
int res = this.userService.addUser(user);
returnCodeUtil.setResult(res > 0);
return returnCodeUtil;
}
@RequestMapping("/register")
public ReturnCodeUtil register(@RequestBody User user) {
return addUser(user);
}
这样做的优点是减少了重复代码,提高了代码的可读性和维护性。同时,将两个方法合并为一个可以减少代码量,简化代码逻辑。
阅读全文