Really, I don't quite understand what is considered a bug in Java.
I've read that you should use an assert
to check your code in only in private functions, but use an if statement to throw an IllegalArgumentException.
What I don't get is, why is the first case is a logic error, but the other case is "the outside user didn't provide the correct arguments"?
Let's say I have two functions:
public boolean isDigit(char c) { return c >= '0' && c <= '9'; }
public int toInt(char c) { return c - '0'; }
In all code I write, before calling toInt
, I would check to make sure it's a digit first, or else it doesn't make sense!
But from what I've read, the user is allowed to make things that don't make sense; the code is supposed to check for that?
To make the code robust, I'd add an assert to make sure the params are right. These are only to check errors while debugging....
public int toInt(char c) { assert isDigit(c); return c - '0'; }
But I've read that's not how you're supposed to do it in Java? You're supposed to do:
public int toInt(char c) {
if (!isDigit(c)) {
throw new IllegalArgumentException("char is not a digit");
}
return c - '0';
}
This is really ugly for me to see, because I should already be checking that the param is valid before calling the function! Is the double check optimized somehow?
When I see the code above, it seems to me, it's as if simple code like this:
char c = '0';
if (isDigit(c)) {
int i = toInt(c);
} else {
doSomethingElse...;
}
becomes like this:
char c = '0';
if (isDigit(c)) {
if(!isDigit(c)) {
throw new IllegalArgumentException("char is not a digit");
}
int i = c - '0';
}
...
So is that normal, that everything is unnecessarily double checked? Is that the Java way of doing stuff?
If so, I want to know how an IllegalArgumentException would ever occur other than an error in logic, because I really don't get it. It really bugs me because to me it makes no sense someone would actually put an argument without first checking that it is valid. Thanks!
In short the question could be: Is it normal that everything is checked for consistency multiple times even though they are known to be correct, and how does it happen that an illegal argument is passed after it's been checked to make sure it's correct?