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

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

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

19条回答
  •  爱一瞬间的悲伤
    2020-11-22 16:16

    Here's the most common use case. Suppose you're switching on an enum value:

    switch (fruit) {
      case apple:
        // do something
        break;
      case pear:
        // do something
        break;
      case banana:
        // do something
        break;
    }
    

    As long as you handle every case, you're fine. But someday, somebody will add fig to your enum and forget to add it to your switch statement. This produces a bug that may get tricky to catch, because the effects won't be felt until after you've left the switch statement. But if you write your switch like this, you can catch it immediately:

    switch (fruit) {
      case apple:
        // do something
        break;
      case pear:
        // do something
        break;
      case banana:
        // do something
        break;
      default:
        assert false : "Missing enum value: " + fruit;
    }
    

提交回复
热议问题