簡體   English   中英

Java中執行空檢查的最優雅方法是什么

[英]What is the most elegant way of doing null checks in Java

舉個例子,假設我們有一個類似於以下代碼的代碼:

String phone = currentCustomer.getMainAddress().getContactInformation().getLandline()

眾所周知,Java中沒有Elvis運算符,並且無法像這樣捕獲NPE:

String phone = null;
try {
    phone = currentCustomer.getMainAddress().getContactInformation().getLandline()
} catch (NullPointerException npe) {}

沒有人會建議。 使用Java 8 Optional是一種解決方案,但是代碼很難看清->遵循以下內容:

String phone = Optional.ofNullable(currentCustomer).flatMap(Customer::getMainAddress)
    .flatMap(Address::getContactInformation)
    .map(ContactInfo::getLandline)
    .orElse(null);

那么,還有其他不犧牲可讀性的強大解決方案嗎?

編輯:下面已經有一些好主意,但是讓我們假設該模型是自動生成的(每次更改都不方便),或者是在需要從源中進行修改的第三方jar中。

問題的“心臟”

此模式currentCustomer.getMainAddress().getContactInformation().getLandline()稱為TrainWreck ,應避免使用。 您是否做到了這一點-不僅具有更好的封裝和更少的耦合代碼,而且作為“副作用”,您不必處理當前面臨的問題。

怎么做?

很簡單, currentCustomer類應該公開一個新方法: getPhoneNumber() ,用戶可以通過這種方式調用: currentCustomer.getPhoneNumber()而不用擔心實現細節(火車殘骸公開了這些細節)。

它能完全解決我的問題嗎?

否。但是現在您可以使用Java 8 optional來調整最后一步。 與問題中的示例不同,當返回的值可能為null ,使用Optionals從方法返回,讓我們看看如何實現(在Customer類中):

Optional<String> getPhoneNumber() {
    Optional<String> phone = Optional.empty();
    try {
        phone = Optional.of(mainAddress.getContactInformation().getLandline());
    } catch (NullPointerException npe) {
        // you might want to do something here: 
        // print to log, report error metric etc
    }
    return phone;
}

根據下面的Per Nick的評論,理想情況下,方法getLandline()將返回Optional<String> ,這樣我們可以跳過吞下異常的不良做法(並在可以避免的情況下引發它們),這也將使我們的代碼更加簡潔

Optional<String> getPhoneNumber() {
    Optional<String> phone = mainAddress.getContactInformation().getLandline();        
    return phone;
}
phone = (currentCustomer.getMainAddress().getContactInformation().getLandline() !=null) ? currentCustomer.getMainAddress().getContactInformation().getLandline() : null;

也許這行得通嗎? Kinda很長,所以我建議也許只是將其分開,但是它仍然應該可讀。

String s = null;
System.out.println(s == null);

要么

String s = null;
if(s == null)System.out.println("Bad Input, please try again");

如果您的問題是對象為null,則應在問題中明確說明...

PhoneObject po = null;
if(po==null) System.out.println("This object is null");

如果您的問題是檢查該行的所有部分是否為空,那么您也應該明確指出...

if(phone == null) return -1;
Customer c = phone.currentCustomer();
if(c == null)return -1;
MainAddress ma = c.getMainAddress();
if(ma == null) return -1;
ContactInfo ci = ma.getContactInformation();
if(ci == null)return -1;
LandLine ll = ci.getLandline();
if(ll == null)return -1;
else return ll.toNumber()//or whatever method

老實說,編寫良好的代碼不應有太多機會返回null。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM