Skip to content

SONARJAVA-5622: Modify rule S7158, extend description to also cover CharSequence #5129

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jun 17, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions rules/S7158/java/rule.adoc
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -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]
Expand All @@ -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
Expand Down