Try-Catch,optional / null和lambda

时间:2016-11-23 14:39:55

标签: java

考虑以下代码:

  • obj在被服务初始化之后没有被修改,但是,由于try / catch块,它不被认为是有效的最终版本。 有没有办法避免这种情况?
  • Optional是否可以被视为避免空值检查的通用方法?在这个例子中,服务会抛出异常而不是返回null,或者总是返回Optional?

    //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));
    

2 个答案:

答案 0 :(得分:6)

将try / catch拆分为一个单独的方法(这通常是一种很好的做法,因为它使代码更具可读性。请参阅Robert Cecil Martin撰写的“清洁代码”)

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,你仍然可以声明变量final,因为你只需要分配一次。

答案 1 :(得分:0)

制作objCopy final

final SomeObject objCopy = obj;
boolean test = someList.stream()
    .anyMatch(o->o.equals(objCopy));