1、怎么让你的代码更优雅
public Info getDetail(Integer id){
Info info = infoService.getInfo(id);
if(info != null){
User user = userService.getUserById(info.getUserId);
if(user != null){
info.setPhone(user.getPhone());
}
if(user != null){
Account account = accountService.getBalance(user.getUserId);
if(account != null){
info.setBalance(account.getBalance());
}
}
}
retrun info;
}
这段代码很常见,功能没什么问题,但是看起来就是不爽。该怎么重构呢?还有列表,如果一个列表里面的很多字段需要从其他服务里面获取字段,该怎么重构更优雅呢。
我能想到的就是卫句了。
public Info getDetail(Integer id){
Info info = infoService.getInfo(id);
if(info == null) return info;
User user = userService.getUserById(info.getUserId);
if(user == null) return info;
info.setPhone(user.getPhone());
Account account = accountService.getBalance(user.getUserId);
if(account != null){
info.setBalance(account.getBalance());
}
retrun info;
}