What do you normally write when you're testing for the return value of indexOf?
if str.indexOf("a") < 0
vs
if str.indexOf("a") == -1
Would one method be preferred over the other?
I'm actually posing this question for any function in any language that returns -1 on error.
I normally prefer the < 0 approach, because if the function is extended to return -2 on some other case, the code would still work.
However, I notice that the == -1 approach is more commonly used. Is there a reason why?
I try to implement the general principle that tests for "error conditions" should be as wide as possible. Hence I would use < 0
rather than == -1
.
This is a principle I was taught during classes in formal methods during my CS degree.
On a simple if
it doesn't matter too much, but on loops it's important to detect any "out of range" condition to ensure that the loop is terminated, and not to assume that the loop termination value will be hit exactly.
Take for example this:
i = 0;
while (i < 10) {
++i;
// something else increments i
}
v.s.
i = 0;
while (i != 10) {
++i;
// something else increments i
}
The latter case could fail - the former case won't.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With