Programming with assertions in Java

By the way, do you refer to assert in Java?

I personally find assertions especially useful for invariants. Take into account that assertion checking is turned off by default in Java. You have to add the -ea flag to enable assertion checking.

In other words, you can test your application in a kind of debug mode, where the program will halt once an assertion is broken. On the other hand, the release application will have its assertion turned off and will not incur time penalty for assertion checking. They will be ignored.

In Java, assertions are far less powerful than exceptions and have totally different meanings. Exceptions are there when something unexpected happens and you have to handle it. Assertions are about the correctness of your code. They are here to confirm that what 'should be' is indeed the case.

My rough policy, especially when working with many developers:

  • public methods: always check arguments and throw IllegalArgumentException when something is wrong
  • private methods: use assertions to check arguments against null pointers and so on
  • complex methods: intermediate assertions to ensure that the intermediate results satisfy requested properties

...but actually, I use them sparsingly. Just where it's critical or error-prone places.


About the minor usage of asserts, I think that was a bad decision to make assertions disabled by default.

About extending Error I suppose it extends Error because Errors are exceptions that are not expected to be caught. And that way, when in your code you have catch(Exception), the assertion isn't cached.

And about usage, the best place is in precoditions, postconditions or in the middle of the code in any invariant you want to check.