One thing that makes good code good is the clarity with which it conveys the intent of the original programmer to maintainers, and the proper
choice of indexOf
methods can help move code from confusing to clear.
If you need to see whether a substring is located beyond a certain point in a string, you can test the indexOf
the substring versus
the target point, or you can use the version of indexOf
which takes a starting point argument. The latter is arguably clearer because the
result is tested against -1, which is an easily recognizable "not found" indicator.
String name = "ismael"; if (name.indexOf("ae") > 2) { // Noncompliant // ... }
String name = "ismael"; if (name.indexOf("ae", 2) > -1) { // ... }