优化这段代码userScoreService.findByUserIdAndModuleAndEventAndPayload(userId, moduleName, eventName, payload).ifPresent(us -> { UserScoreEntity userScoreByDel = userScoreService.findByUserIdAndModuleAndEventAndPayload(userId, moduleName, "取消" + eventName, payload).orElseGet(() -> { UserScoreEntity usd = new UserScoreEntity(); usd.setUserId(userId); usd.setModule(moduleName); usd.setEvent("取消" + eventName); Integer total = userScoreService.findTotalScoreByUserId(userId); if (total <= us.getScore()) { usd.setScore((short) -total); usd.setTotal(0); } else { usd.setScore((short) -us.getScore()); usd.setTotal(total - us.getScore()); } usd.setPayload(event.getPayload()); usd.setOperationTime(event.getSendTime()); return usd; }); if (Objects.isNull(userScoreByDel.getId())) { userScoreService.save(userScoreByDel); } });
时间: 2024-02-14 10:26:26 浏览: 138
使用dumpchk.exe和pstat.exe去分析Windows蓝屏的原因
5星 · 资源好评率100%
优化后的代码如下:
```java
String cancelEventName = "取消" + eventName;
Optional<UserScoreEntity> optionalUserScore = userScoreService.findByUserIdAndModuleAndEventAndPayload(userId, moduleName, eventName, payload);
if (optionalUserScore.isPresent()) {
UserScoreEntity userScore = optionalUserScore.get();
UserScoreEntity userScoreByDel = userScoreService.findByUserIdAndModuleAndEventAndPayload(userId, moduleName, cancelEventName, payload).orElseGet(() -> {
UserScoreEntity usd = new UserScoreEntity();
usd.setUserId(userId);
usd.setModule(moduleName);
usd.setEvent(cancelEventName);
Integer total = userScoreService.findTotalScoreByUserId(userId);
if (total <= userScore.getScore()) {
usd.setScore((short) -total);
usd.setTotal(0);
} else {
usd.setScore((short) -userScore.getScore());
usd.setTotal(total - userScore.getScore());
}
usd.setPayload(event.getPayload());
usd.setOperationTime(event.getSendTime());
return usd;
});
if (userScoreByDel.getId() == null) {
userScoreService.save(userScoreByDel);
}
}
```
优化说明:
- 将重复使用的字符串 "取消" + eventName 提取为一个变量 cancelEventName,减少重复计算。
- 通过 optionalUserScore.isPresent() 判断是否存在对应的 UserScoreEntity 实例,避免重复查询。
- 使用 userScore 变量代替 us,提高代码可读性。
- 对于 userScoreByDel.getId() 的判断,使用 userScoreByDel.getId() == null 替代 Objects.isNull(userScoreByDel.getId())。
- 代码格式化,提高可读性。
阅读全文