考虑以下代码:
- OBJ在通过服务进行INTIAL后未经修改,但是由于尝试/捕获块,因此并未被认为是有效的。有没有办法避免这种情况?
-
是否可以将可选的视为视为避免零检查的通用方法?在此示例中,服务会抛出异常或返回null,还是始终返回可选?
//to be used outside try/catch block, object must be initialized as null SomeObject obj = null; try { obj = someService.getSomeObject(); } catch (ServiceException e) { LOG.error("Something nasty happened", e); } //the service could have returned a null object if(obj == null) { LOG.error("Obj is null"); } //to be used in a lambda, object must be final SomeObject objCopy = obj; boolean test = someList.stream() .anyMatch(o->o.equals(objCopy));
只是将尝试/捕捉到单独的方法(这通常是很好的做法,因为它使代码更可读。请参阅Robert Cecil Martin的" Clean Code")
final Optional<SomeObject> obj = getObjFromService(someService);
...
private Optional<SomeObject> getObjFromService(Service someService) {
try {
return Optional.of(someService.getSomeObject());
} catch (ServiceException e) {
LOG.error("Something nasty happened", e);
}
return Optional.empty();
}
您也可以从方法getObjFromService
返回null,您仍然可以声明变量最终,因为您仅分配了一次。
使objcopy final
final SomeObject objCopy = obj;
boolean test = someList.stream()
.anyMatch(o->o.equals(objCopy));