Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for testing return value of indexOf

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?

like image 913
Justin Wong Avatar asked Apr 16 '12 14:04

Justin Wong


1 Answers

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.

like image 167
Alnitak Avatar answered Oct 04 '22 20:10

Alnitak