rspec/rules/S2692/java/rule.adoc
Fred Tingaud 0bbdb53a0c
Modify Rule S2692: LaYC indexOf
Co-authored-by: Amélie Renard <44666826+amelie-renard-sonarsource@users.noreply.github.com>
2023-06-16 09:50:40 +02:00

39 lines
874 B
Plaintext

== Why is this an issue?
Most checks against an `indexOf` value compare it with -1 because 0 is a valid index. Checking against `> 0` ignores the first element, which is likely a bug.
[source,java]
----
String name = "ishmael";
if (name.indexOf("ish") > 0) { // Noncompliant
// ...
}
----
Moreover, if the intent is merely to check the inclusion of a value in a `String` or a `List`, consider using the `contains` method instead.
[source,java]
----
String name = "ishmael";
if (name.contains("ish") {
// ...
}
----
If the intent is really to skip the first element, comparing it with `>=1` will make it more straightforward.
[source,java]
----
String name = "ishmael";
if (name.indexOf("ish") >= 1) {
// ...
}
----
This rule raises an issue when an `indexOf` value retrieved from a `String` or a `List` is tested against `> 0`.
include::../rspecator.adoc[]