diff --git a/rules/S7158/java/rule.adoc b/rules/S7158/java/rule.adoc index 7eb6bab3efe..afec24a5a7b 100644 --- a/rules/S7158/java/rule.adoc +++ b/rules/S7158/java/rule.adoc @@ -1,6 +1,7 @@ == Why is this an issue? Calling `String.isEmpty()` clearly communicates the code's intention, which is to test if the string is empty. Using `String.length() == 0` is less direct and makes the code less readable. +This preference for `isEmpty()` extends to all `CharSequence` objects, including `StringBuilder` and `StringBuffer`. == How to fix it @@ -13,6 +14,12 @@ if ("string".length() == 0) { /* … */ } // Noncompliant if ("string".length() > 0) { /* … */ } // Noncompliant ---- +[source,java,diff-id=2,diff-type=noncompliant] +---- +StringBuilder sb = new StringBuilder(); +... +if (sb.length() == 0) { /* … */ } // Noncompliant +---- ==== Compliant solution [source,java,diff-id=1,diff-type=compliant] @@ -21,6 +28,12 @@ if ("string".isEmpty()){ /* … */ } if (!"string".isEmpty()){ /* … */ } ---- +[source,java,diff-id=2,diff-type=compliant] +---- +StringBuilder sb = new StringBuilder(); +... +if (sb.isEmpty()) { /* … */ } +---- == Resources === Documentation