2016-11-23 51 views
0

考虑下面的代码:的try-catch,可选/空,拉姆达

  • obj是不会被修改之后被intialised的服务,但是,由于try/catch块,它不被视为有效决赛。 有没有办法避免这种情况?
  • 是否可选可能被认为是避免空检查的通用方法?在这个例子中,服务会抛出异常,或者返回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)); 
    
+0

'它不被认为是有效的最终'你是什么意思? – 2016-11-23 14:45:03

+0

@LutzHorn,一个变量被认为是有效的最终的,如果它的值初始化后永远不会改变。 –

回答

3

只是分裂尝试/捕捉到一个单独的方法(这通常是很好的做法,因为它使代码更易读。请参阅“清洁守则”由罗伯特·塞西尔·马丁)

final 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,因为您只分配一次。

0

使objcopy把最后

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

我在这个目的下创建了一个objCopy,它在这个时候实际上是最终的 –

+0

在原始问题中没有。抱歉 –