2016-11-23 53 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

在原始問題中沒有。抱歉 –