2009-02-19 76 views
12

我有點在等待這個問題的'不'的答案。你可以在if子句中存儲一個變量嗎?

我感興趣的是如果您可以在if-clause中檢查時同時保存一個變量。

假設我有這個代碼。

if(foo!=null){ 
    if(foo.getBar()!=null){ 
    Bar bar = foo.getBar(); 
    System.out.println("Success: " + bar); 
    } else { 
    System.out.println("Failure."); 
    } 
} else { 
    System.out.println("Failure."); 
} 

我現在正在處理「失敗」 - 獨立的狀態,即使結果是相同的。我可以像這樣把它們弄到一起:

if(foo!=null && foo.getBar()!=null){ 
    Bar bar = foo.getBar(); 
    System.out.println("Success: " + bar); 
} else { 
    System.out.println("Failure."); 
} 

已經有很多整齊的代碼了。如果foo爲null,它會停在那裏,不會嘗試foo.getBar(在if),所以我不會得到一個NPE。我想提升的最後一件事情,以及主要問題:我真的給了兩次foo.getBar()嗎?如果getBar()會是一個非常繁重的操作,那麼離開第二個相同的調用將會很好。所以,我想知道是否有某種方式可以做類似的東西,以這樣的:

if(foo!=null && (Bar bar = foo.getBar())!=null){ 
    Bar bar = foo.getBar(); 
    System.out.println("Success: " + bar); 
} else { 
    System.out.println("Failure."); 
} 

我將不得不如果再次是將它分解到兩個不同的,如果我想這樣做

Bar bar = foo.getBar(); 
if (bar!=null) ... 
+0

順便說一下,這是「失敗」。 – 2009-02-19 14:53:43

回答

25

這是最接近你可以得到:

Bar bar; 
if(foo!=null && (bar = foo.getBar())!=null){ 
    System.out.println("Success: " + bar); 
} else { 
    System.out.println("Failiure."); 
} 
+0

是的,這實際上工作。我嘗試在if內部有(Bar bar = foo.getBar())!= null,但是java似乎並不希望在if子句中有Object的初始化。謝謝! – 2009-02-19 07:59:06

10

我有

BufferedReader br = // create reader 
String line 
while ((line = br.readLine()) != null) { 
    // process the line 
} 

所以,是的,你可以做一個任務,結果關閉,這將是左邊的變量,然後你就可以檢查:從一個BufferedReader進行遍歷時,在線路使用的技術。但是,在測試中聲明變量是不合法的,因爲它們只會被限制在該表達式中。

7

,如果你想限制吧吧的我要補充{和}圍繞着邁克爾發佈的代碼的範圍。

 
void foo() 
{ 
    // some code ... 

    // this block limits the scope of "Bar bar" so that the rest of the method cannot see 
    // it. 
    { 
     Bar bar; 
     if(foo!=null && (bar = foo.getBar())!=null){ 
      System.out.println("Success: " + bar); 
     } else { 
      System.out.println("Failiure."); 
     } 
    } 
} 

如果有意義,您可能還想檢入空對象模式。我個人試圖避免事情是空的,如果我可以...真的想想如果你想null或被允許。

2

從部門「我的編程語言比您的編程語言更好」:在Groovy中,您可以使用「?」。運營商:

Bar bar = foo?.bar 
if (bar != null) { 
} 

在Java中,這是一個好模式(*):

Bar bar = foo == null ? null : foo.getBar(); 
if (bar != null) { 
} 

*:有些事情,你可以在你的指尖保存。

1

三點完全不能回答這個問題:

null是邪惡的。不要編寫返回它的方法。您的示例問題將消失。

我想你可能會錯過封裝。而不是foo.getBar()foo的界面可以做成這樣,你執行一個「告訴別人問題」的操作?

表達式中的副作用往往會導致錯誤的代碼。選擇更多,更簡單的線條來減少錯誤的線條。如果在訪問緩衝區時使用++來增加索引或類似的迭代器樣式算法,通常會發生異常。

相關問題