Skip to content Skip to sidebar Skip to footer

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 ot

Solution 1:

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.

Solution 2:

I would also prefer the <0 approach. The reason why == -1 approach is widely used is because of the fact that the functions would indeed return -1 if the index is missing and the case of "extended function" will never happen, according to Java documentation.

Solution 3:

In almost all cases advisable to stick to the Java doc as closely as possibly. See Java Doc: http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#indexOf%28int%29

... according to it: -1 will be returned.

So I would always check for -1. If you have a specific value to check, its safer to check for that specific value, to protect against future code changes in java api.

For example, if you get a -2, that means that somethings is seriously wrong in your JVM. It doesn't mean "not found". It would be better for code to proceed to and cause an Exception/Error.

Solution 4:

According to javadoc indexOf is always supposed to return -1 if character does not occur in sequence http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#indexOf%28int%29

Solution 5:

As Sandeep Nair points out the javaDoc explains it, but I want to comment a bit.

Both would work fine and I wouldn't say one is "better" than the other. The reason many people write == -1 is that there is a general convention that search methods return -1 if "stuff cannot be found". We cannot use 0 since they are used as indices in arrays etc.

So, it's a matter of opinion. As long as the convention stays, it doesn't matter.

Post a Comment for "Best Practice For Testing Return Value Of Indexof"