2011-02-19 141 views

回答

2

斷言可以關閉(實際上,它們通常是),所以它們對於驗證用戶輸入沒有用處,例如。

29

Validate.isTrue和'assert'服務完全不同的目的。

斷言
Java的斷言語句通常用於記錄(藉助斷言 )下可調用何種情況的方法,並 什麼調用者可以期待是真實的之後。在運行時可以選擇性地檢查斷言 ,如果它們不成立,將導致AssertionError 異常。

在設計合同中,斷言可以用來定義 前後置條件以及類不變式。如果在運行時間 這些被檢測爲不成立,則這指向系統中的設計或實現問題。

Validate.isTrue
org.apache.commons.lang.Validate是不同的。它提供了一組簡單的 類似JUnit的方法來檢查條件,如果條件不成立,則拋出 「IllegalArgumentException」。

它通常用於公共API應該容忍對輸入不好的 輸入。在這種情況下,其合同可能承諾在錯誤輸入時拋出IllegalArgumentException。 Apache Validate提供了 這是一個方便的簡寫。

由於引發了IllegalArgumentException,因此使用Apache的Validate檢查後置條件或不變量是沒有意義的 。 同樣,使用'斷言'進行用戶輸入驗證是不正確的,因爲斷言檢查可以在運行時被禁用,所以 。

同時使用
這是可能的,但是,在同一時間,不同的目的使用它們,儘管 。在這種情況下,合同應明確 需要在輸入的某些類型 上引發IllegalArgumentException。然後通過Apache Validate實現。 然後簡單地聲明不變量和後置條件,以及 儘可能多的其他先決條件(例如影響對象的狀態 )。例如:

public int m(int n) { 
    // the class invariant should hold upon entry; 
    assert this.invariant() : "The invariant should hold."; 

    // a precondition in terms of design-by-contract 
    assert this.isInitialized() : "m can only be invoked after initialization."; 

    // Implement a tolerant contract ensuring reasonable response upon n <= 0: 
    // simply raise an illegal argument exception. 
    Validate.isTrue(n > 0, "n should be positive"); 

    // the actual computation. 
    int result = complexMathUnderTrickyCircumstances(n); 

    // the postcondition. 
    assert result > 0 : "m's result is always greater than 0."; 
    assert this.processingDone() : "processingDone state entered after m."; 
    assert this.invariant() : "Luckily the invariant still holds as well."; 

    return result; 
} 

的更多信息:

  • 伯特蘭·邁耶, 「重合同應用設計」,IEEE計算機,1992年(pdf
  • Johsua布洛赫。 Effective Java,第二版,第38項。檢查參數的有效性。(google books
+1

Johsua Bloch。 *有效的Java *,項目23:檢查參數的有效性。 – artdanil 2013-08-15 21:47:49

1

@thilo對assert關鍵字是正確的,但考慮一下像Assertion一樣的Spring Assert。

查看來自Guava的ConditionalFailuresExplained

  • 先決條件「你搞砸了(調用者)。」
  • 聲明「我搞砸了。」 「
  • 驗證」有人依靠我搞砸了。「
相關問題