Java assertions underused

In "Effective Java", Joshua Bloch suggested (in the "Check parameters for validity" topic) that (sort of like a simple rule to adopt), for public methods, we shall validate the arguments and throw a necessary exception if found invalid, and for non-public methods (which are not exposed and you as the user of them should ensure their validity), we can use assertions instead.


It's an abuse of assertions to use them to test user input. Throwing an IllegalArgumentException on invalid input is more correct, as it allows the calling method to catch the exception, display the error, and do whatever it needs to (ask for input again, quit, whatever).

If that method is a private method inside one of your classes, the assertion is fine, because you are just trying to make sure you aren't accidentally passing it a null argument. You test with assertions on, and when you have tested all the paths through and not triggered the assertion, you can turn them off so that you aren't wasting resources on them. They are also useful just as comments. An assert at the start of a method is good documentation to maintainers that they should be following certain preconditions, and an assert at the end with a postcondition documents what the method should be doing. They can be just as useful as comments; moreso, because with assertions on, they actually TEST what they document.

Assertions are for testing/debugging, not error-checking, which is why they are off by default: to discourage people from using assertions to validate user input.


assertions are, in theory, for testing invariants, assumptions that must be true in order for the code to complete properly.

The example shown is testing for valid input, which isn't a typical usage for an assertion because it is, generally, user supplied.

Assertions aren't generally used in production code because there is an overhead and it is assumed that situations where the invariants fail have been caught as coding errors during development and testing.

Your point about them coming "late" to java is also a reason why they aren't more widely seen.

Also, unit testing frameworks allow for some of the need for programmatic assertions to be external to the code being tested.

Tags:

Java

Assertion