Java assertions underused

Solution 1:

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.

Solution 2:

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.

Solution 3:

From Programming with Assertions

By default, assertions are disabled at runtime. Two command-line switches allow you to selectively enable or disable assertions.

This means that if you don't have complete control over the run-time environment, you can't guarantee that the assertion code will even be called. Assertions are meant to be used in a test-environment, not for production code. You can't replace exception handling with assertions because if the user runs your application with assertions disabled (the default), all of your error handling code disappears.

Solution 4:

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.