What does the Java assert keyword do, and when should it be used?

前端 未结 19 1485
眼角桃花
眼角桃花 2020-11-22 15:58

What are some real life examples to understand the key role of assertions?

19条回答
  •  有刺的猬
    2020-11-22 16:29

    Here's another example. I wrote a method that finds the median of the values in two sorted arrays. The method assumes the arrays are already sorted. For performance reasons, it should NOT sort the arrays first, or even check to ensure they're sorted. However, it's a serious bug to call this method with unsorted data, and we want those bugs to get caught early, in the development phase. So here's how I handled those seemingly conflicting goals:

    public static int medianOf(int[] a, int[] b) {
      assert assertionOnlyIsSorted(a);      // Assertion is order n
      assert assertionOnlyIsSorted(b);
      ... // rest of implementation goes here. Algorithm is order log(n)
    }
    
    public static boolean assertionOnlyIsSorted(int[] array) {
      for (int i=1; i

    This way, the test, which is slow, is only performed during the development phase, where speed is less important than catching bugs. You want the medianOf() method to have log(n) performance, but the "is sorted" test is order n. So I put it inside an assertion, to limit its use to the development phase, and I give it a name that makes it clear it's not suitable for production.

    This way I have the best of both worlds. In development, I know that any method that calls this incorrectly will get caught and fixed. And I know that the slow test to do so won't affect performance in production. (It's also a good illustration of why you want to leave assertions off in production, but turn them on in development.)

提交回复
热议问题