New rule to suggest "string".length() == 0 -> "string".isEmpty()

There should be a new rule to suggest a change of

"string".length() == 0

to

"string".isEmpty()

and

"string".length() > 0

to

!"string".isEmpty()

and

"string".trim().length() == 0

to

"string".isBlank()

and

"string".trim().length() > 0

to

!"string".isBlank()

And please add a good quick fix. It’s so easy to indroduce regressions with negation.

On a side node this quick fix should also be applied java:S1155.

2 Likes

Hey Marvin.

I’ve moved your post to this category:

This category has a pretty detailed template post we ask users to fill out when suggesting a new rule. Can you review it and add the missing information?

Perfect! Thanks for moving.

I need privileges to edit the post through.

Feel free to just add a new comment.

Title:
Use String.isEmpty() and isBlank() instead of a length check (with trim()) against 0.

Description:
The String.length() check against 0 is much more verbose than a simple call of isEmpty() or isBlank(). In case of isBlank() the string needs to be trim’ed before applying the length check and the result of trim() is discarded right away.

Non compliant code:

if ("string".length() == 0)

if ("string".length() > 0)

if ("string".trim().length() == 0)

if ("string".trim().length() > 0)

Compliant code:

if ("string".isEmpty())

if (!"string".isEmpty())

if ("string".isBlank())

if (!"string".isBlank())

Exceptions to non compliant code:

if ("string".length() > 1)

if ("string".trim().length() == 10)
  • type : Code Smell

Please add a good quick fix. It’s so easy to indroduce regressions with negation.
On a side node this quick fix should also be applied to java:S1155.

1 Like

Hello @mfroehlich, thanks for reaching out with such an interesting rule idea!

We do support something similar for empty/not-empty collections, see S1155 and S6529. It is a great idea to extend it to strings and to cover blank/not-blank as well.

I created the implementation tickets for sonar-java and sonar-kotlin. You can track their progress on SONARJAVA-4606 and SONARKT-360.