优化这段代码//统一数据删除 public int delete(CommonUse commonUse){ String userFlag = commonUse.getUserFlag(); if("1".equals(userFlag)){ return planterDao.delete(commonUse); } return -1; } //通过key查询所有的信息 public CommonUse getAllInfo(String key,String userFlag){ CommonUse commonUse = new CommonUse(); commonUse.setPlanterOnlyKey(key); CommonUse commonUse1 = commonUseDao.searchOneByOnlyKey(commonUse); commonUse1.setUserFlag(userFlag); return commonUse1; }
时间: 2024-03-12 10:42:57 浏览: 29
为了优化这段代码,可以考虑以下两点:
1. 增加参数校验
在第二个方法 `getAllInfo` 中,应该增加对传入参数的校验,比如判断 `key` 是否为空,如果为空则直接返回 null。这样可以避免出现空指针异常等问题。
2. 将返回值改为 Optional
在第二个方法 `getAllInfo` 中,可以将返回值改为 `Optional<CommonUse>` 类型,这样可以避免返回 null 值带来的风险,同时也能更好地处理查询结果为空的情况。
下面是优化后的代码:
```
// 统一数据删除
public int delete(CommonUse commonUse) {
String userFlag = commonUse.getUserFlag();
if ("1".equals(userFlag)) {
return planterDao.delete(commonUse);
}
return -1;
}
// 通过key查询所有的信息
public Optional<CommonUse> getAllInfo(String key,String userFlag) {
if (StringUtils.isBlank(key)) {
return Optional.empty();
}
CommonUse commonUse = new CommonUse();
commonUse.setPlanterOnlyKey(key);
CommonUse commonUse1 = commonUseDao.searchOneByOnlyKey(commonUse);
if (commonUse1 != null) {
commonUse1.setUserFlag(userFlag);
return Optional.of(commonUse1);
}
return Optional.empty();
}
```
优化后的代码增加了参数校验和返回值改为 `Optional`,可以更加健壮和安全地执行相关操作。