@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-03-11 08:49:58 浏览: 56
可以将这两个方法中的重复代码提取出来,避免重复的代码出现。重构后的代码如下所示:
```java
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/add")
public ResultVO addUser(@Validated @RequestBody User user) {
return addUserOrRegister(user);
}
@PostMapping("/register")
public ResultVO register(@Validated @RequestBody User user) {
return addUserOrRegister(user);
}
private ResultVO addUserOrRegister(User user) {
if (user == null || user.getUserFlag() == null) {
return ResultVO.fail("参数错误");
}
userService.addUser(user);
return ResultVO.success();
}
}
```
通过提取公共方法,代码变得更加简洁易读,避免了重复代码的出现,提高了代码的可维护性和可扩展性。同时,使用统一的ResultVO返回格式,避免了使用ReturnCodeUtil。
阅读全文