Java – best practice for testing indexof return values
What do you usually write when testing the return value of indexof?
if str.indexOf("a") < 0
VS
if str.indexOf("a") == -1
Is one method more popular than another?
I'm actually asking this question for any function in any language, returning - 1 when an error occurs
I usually prefer the < 0 method because if the function is extended to return - 2 in some other cases, the code can still work However, I notice that the = = - 1 method is more commonly used Is there a reason?
Solution
I try to implement the general principle that "error condition" testing should be as wide as possible So I'll use < 0 instead of = = - 1 This is the principle I taught in the formal method course during my CS degree A simple if it doesn't matter too much, but in a loop, it's important to detect any "out of range" conditions to ensure loop termination, and don't assume that the loop termination value will be completely hit Take this as an example:
i = 0; while (i < 10) { ++i; // something else increments i }
V.S.
i = 0; while (i != 10) { ++i; // something else increments i }
The latter may fail – the former does not