Is Java assert broken?

后端 未结 12 784
走了就别回头了
走了就别回头了 2020-12-29 23:33

While poking around the questions, I recently discovered the assert keyword in Java. At first, I was excited. Something useful I didn\'t already know! A more

12条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-30 00:09

    assert is a useful piece of Design by Contract. In that context, assertions can be used in:

    • Precondition checks.
    • Postcondition checks.
    • Intermediate result checks.
    • Class invariant checks.

    Assertions can be expensive to evaluate (take, for example, the class invariant, which must hold before and after calling any public method of your class). Assertions are typically wanted only in debug builds and for testing purposes; you assert things that can't happen - things which are synonymous of having a bug. Assertions verify your code against its own semantics.

    Assertions are not an input validation mechanism. When input could really be correct or wrong in the production environment, i.e. for input-output layers, use other methods, such as exceptions or good old conditional checks.

提交回复
热议问题