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
assert
is a useful piece of Design by Contract. In that context, assertions can be used in:
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.