For example when using Preconditions.checkArgument, is the error message supposed to reflect the passing case or the failing case of the check in question?
import static com.google.common.base.Preconditions.*;
void doStuff(int a, int b) {
checkArgument(a == b, "a == b");
// OR
checkArgument(a == b, "a != b");
}
For precondition checks, stating the requirement in the exception detail message is more informative than simply stating the facts. It also leads to a lot more naturally reading code:
The documentation provides the following example:
Two things are of note:
Following that example, a better message would be:
You can even go a step further and capture the values of
aandbin the exception message (see Effective Java 2nd Edition, Item 63: Include failure capture information in detail messages):The alternative of stating facts is less natural to read in code:
Note how awkward it is to read in Java code one boolean expression, followed by a string that contradicts that expression.
Another downside to stating facts is that for complicated preconditions, it’s potentially less informative, because the user may already know of the fact, but not what the actual requirements are that is being violated.
Related questions