Repository navigation
SONARJAVA-7157: Implemented rule S9432 Strings should not be trimmed or stripped just to check if they are blank #6332
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
Closed
Closed
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
0d0a17c
Add rule metadata
romainbrenguier 68e2c15
Add failing reproducer
romainbrenguier 6089bfa
Implement rule
romainbrenguier 987a0da
Qualify S9432 message for trim()-based checks
romainbrenguier a0eaa72
Update ruling results for PR #6332 (#6334)
github-actions[bot] a21986e
Increase S9432 coverage and remove unreachable branch
romainbrenguier 6a682bc
Update ruling results for PR #6332 (#6345)
github-actions[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
5 changes: 5 additions & 0 deletions
5
its/ruling/src/test/resources/expected/eclipse-jetty-similar-to-main/java-S9432.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| { | ||
| "eclipse-jetty:jetty-server/src/main/java/org/eclipse/jetty/server/MultiPartFormInputStream.java": [ | ||
| 143 | ||
| ] | ||
| } |
13 changes: 13 additions & 0 deletions
13
its/ruling/src/test/resources/expected/eclipse-jetty/java-S9432.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| { | ||
| "eclipse-jetty:jetty-server/src/main/java/org/eclipse/jetty/server/MultiPartFormInputStream.java": [ | ||
| 143 | ||
| ], | ||
| "eclipse-jetty:jetty-util/src/main/java/org/eclipse/jetty/util/HttpCookieStore.java": [ | ||
| 84 | ||
| ], | ||
| "eclipse-jetty:jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlConfiguration.java": [ | ||
| 1324, | ||
| 1333, | ||
| 1485 | ||
| ] | ||
| } |
73 changes: 73 additions & 0 deletions
73
java-checks-test-sources/default/src/main/java/checks/S9432CheckSample.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| package checks; | ||
|
|
||
| public class S9432CheckSample { | ||
|
|
||
| boolean hasContent(String input) { | ||
| boolean result; | ||
| result = input.trim().length() == 0; // Noncompliant {{Use "isBlank()" on the original string instead, if Unicode whitespace should be treated as blank and control characters as non-blank.}} | ||
| result = input.trim().length() <= 0; // Noncompliant {{Use "isBlank()" on the original string instead, if Unicode whitespace should be treated as blank and control characters as non-blank.}} | ||
| result = input.trim().length() < 1; // Noncompliant {{Use "isBlank()" on the original string instead, if Unicode whitespace should be treated as blank and control characters as non-blank.}} | ||
| result = input.strip().length() != 0; // Noncompliant {{Use "isBlank()" on the original string instead.}} | ||
| result = input.strip().length() > 0; // Noncompliant {{Use "isBlank()" on the original string instead.}} | ||
| result = input.strip().length() >= 1; // Noncompliant {{Use "isBlank()" on the original string instead.}} | ||
| result = 0 == input.trim().length(); // Noncompliant {{Use "isBlank()" on the original string instead, if Unicode whitespace should be treated as blank and control characters as non-blank.}} | ||
| result = 0 >= input.trim().length(); // Noncompliant {{Use "isBlank()" on the original string instead, if Unicode whitespace should be treated as blank and control characters as non-blank.}} | ||
| result = 1 > input.trim().length(); // Noncompliant {{Use "isBlank()" on the original string instead, if Unicode whitespace should be treated as blank and control characters as non-blank.}} | ||
| result = 0 != input.strip().length(); // Noncompliant {{Use "isBlank()" on the original string instead.}} | ||
| result = 0 < input.strip().length(); // Noncompliant {{Use "isBlank()" on the original string instead.}} | ||
| result = 1 <= input.strip().length(); // Noncompliant {{Use "isBlank()" on the original string instead.}} | ||
| result = input.trim().isEmpty(); // Noncompliant {{Use "isBlank()" on the original string instead, if Unicode whitespace should be treated as blank and control characters as non-blank.}} | ||
| result = !input.strip().isEmpty(); // Noncompliant {{Use "isBlank()" on the original string instead.}} | ||
| result = input.trim().isBlank(); // Noncompliant {{Use "isBlank()" on the original string instead, if Unicode whitespace should be treated as blank and control characters as non-blank.}} | ||
| result = input.strip().isBlank(); // Noncompliant {{Use "isBlank()" on the original string instead.}} | ||
| result = (input.trim().length()) == 0; // Noncompliant {{Use "isBlank()" on the original string instead, if Unicode whitespace should be treated as blank and control characters as non-blank.}} | ||
| result = 0 < ((input.strip().length())); // Noncompliant {{Use "isBlank()" on the original string instead.}} | ||
| result = (input.trim()).isEmpty(); // Noncompliant {{Use "isBlank()" on the original string instead, if Unicode whitespace should be treated as blank and control characters as non-blank.}} | ||
| return result; | ||
| } | ||
|
|
||
| void validUses(String input) { | ||
| boolean blank = input.isBlank(); | ||
| boolean present = !input.isBlank(); | ||
| boolean longEnough = input.trim().length() > 1; | ||
| boolean exactLength = input.strip().length() == 5; | ||
| boolean otherComparisons = input.trim().length() != 2 || input.trim().length() <= 1 || input.trim().length() < 2 || input.trim().length() >= 2 | ||
| || 2 != input.trim().length() || 1 >= input.trim().length() || 2 > input.trim().length() || 2 <= input.trim().length() || 5 == input.trim().length() || 0 > input.trim().length(); | ||
| int trimmedLength = input.trim().length(); | ||
| boolean sumIsZero = input.trim().length() + trimmedLength == 0; | ||
| boolean parenthesizedSum = (input.strip().length()) + 1 > 0; | ||
| boolean matches = input.trim().equals("value"); | ||
| String normalized = input.trim(); | ||
| audit(input.strip()); | ||
| audit(normalized + blank + present + longEnough + exactLength + matches + sumIsZero + parenthesizedSum + otherComparisons); | ||
| } | ||
|
|
||
| void audit(String input) { | ||
| } | ||
|
|
||
| static class TextBuffer { | ||
| TextBuffer trim() { | ||
| return this; | ||
| } | ||
|
|
||
| TextBuffer strip() { | ||
| return this; | ||
| } | ||
|
|
||
| int length() { | ||
| return 0; | ||
| } | ||
|
|
||
| boolean isEmpty() { | ||
| return true; | ||
| } | ||
|
|
||
| boolean isBlank() { | ||
| return true; | ||
| } | ||
| } | ||
|
|
||
| boolean customText(TextBuffer input) { | ||
| return input.trim().length() == 0 || input.strip().isEmpty() || input.trim().isBlank(); | ||
| } | ||
| } |
129 changes: 129 additions & 0 deletions
129
java-checks/src/main/java/org/sonar/java/checks/S9432Check.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,129 @@ | ||
| /* | ||
| * SonarQube Java | ||
| * Copyright (C) SonarSource Sàrl | ||
| * mailto:info AT sonarsource DOT com | ||
| * | ||
| * You can redistribute and/or modify this program under the terms of | ||
| * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. | ||
| * | ||
| * This program is distributed in the hope that it will be useful, | ||
| * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | ||
| * See the Sonar Source-Available License for more details. | ||
| * | ||
| * You should have received a copy of the Sonar Source-Available License | ||
| * along with this program; if not, see https://sonarsource.com/license/ssal/ | ||
| */ | ||
| package org.sonar.java.checks; | ||
|
|
||
| import java.util.List; | ||
| import javax.annotation.Nullable; | ||
| import org.sonar.check.Rule; | ||
| import org.sonar.java.model.ExpressionUtils; | ||
| import org.sonar.java.model.LiteralUtils; | ||
| import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; | ||
| import org.sonar.plugins.java.api.JavaVersion; | ||
| import org.sonar.plugins.java.api.JavaVersionAwareVisitor; | ||
| import org.sonar.plugins.java.api.semantic.MethodMatchers; | ||
| import org.sonar.plugins.java.api.tree.BinaryExpressionTree; | ||
| import org.sonar.plugins.java.api.tree.ExpressionTree; | ||
| import org.sonar.plugins.java.api.tree.MemberSelectExpressionTree; | ||
| import org.sonar.plugins.java.api.tree.MethodInvocationTree; | ||
| import org.sonar.plugins.java.api.tree.Tree; | ||
|
|
||
| @Rule(key = "S9432") | ||
| public class S9432Check extends IssuableSubscriptionVisitor implements JavaVersionAwareVisitor { | ||
|
|
||
| private static final String MESSAGE = "Use \"isBlank()\" on the original string instead."; | ||
| private static final String TRIM_MESSAGE = "Use \"isBlank()\" on the original string instead, " | ||
| + "if Unicode whitespace should be treated as blank and control characters as non-blank."; | ||
| private static final String STRING_TYPE = "java.lang.String"; | ||
|
|
||
| private static final MethodMatchers WHITESPACE_REMOVAL_METHODS = MethodMatchers.create() | ||
| .ofTypes(STRING_TYPE) | ||
| .names("trim", "strip") | ||
| .addWithoutParametersMatcher() | ||
| .build(); | ||
|
|
||
| private static final MethodMatchers BLANKNESS_METHODS = MethodMatchers.create() | ||
| .ofTypes(STRING_TYPE) | ||
| .names("isEmpty", "isBlank") | ||
| .addWithoutParametersMatcher() | ||
| .build(); | ||
|
|
||
| private static final MethodMatchers LENGTH_METHOD = MethodMatchers.create() | ||
| .ofTypes(STRING_TYPE) | ||
| .names("length") | ||
| .addWithoutParametersMatcher() | ||
| .build(); | ||
|
|
||
| @Override | ||
| public boolean isCompatibleWithJavaVersion(JavaVersion version) { | ||
| return version.asInt() >= 11; | ||
| } | ||
|
|
||
| @Override | ||
| public List<Tree.Kind> nodesToVisit() { | ||
| return List.of(Tree.Kind.METHOD_INVOCATION); | ||
| } | ||
|
|
||
| @Override | ||
| public void visitNode(Tree tree) { | ||
| MethodInvocationTree invocation = (MethodInvocationTree) tree; | ||
| MethodInvocationTree removalInvocation = whitespaceRemovalInvocation(invocation); | ||
| if (removalInvocation == null) { | ||
| return; | ||
| } | ||
| if (BLANKNESS_METHODS.matches(invocation) || (LENGTH_METHOD.matches(invocation) && isEmptinessCheck(invocation))) { | ||
| String message = "trim".equals(removalInvocation.methodSymbol().name()) ? TRIM_MESSAGE : MESSAGE; | ||
| reportIssue(removalInvocation, message); | ||
| } | ||
| } | ||
|
|
||
| @Nullable | ||
| private static MethodInvocationTree whitespaceRemovalInvocation(MethodInvocationTree invocation) { | ||
| ExpressionTree receiver = receiver(invocation); | ||
| if (receiver instanceof MethodInvocationTree receiverInvocation && WHITESPACE_REMOVAL_METHODS.matches(receiverInvocation)) { | ||
| return receiverInvocation; | ||
| } | ||
| return null; | ||
| } | ||
|
|
||
| @Nullable | ||
| private static ExpressionTree receiver(MethodInvocationTree invocation) { | ||
| if (invocation.methodSelect() instanceof MemberSelectExpressionTree memberSelect) { | ||
| return ExpressionUtils.skipParentheses(memberSelect.expression()); | ||
| } | ||
| return null; | ||
| } | ||
|
|
||
| private static boolean isEmptinessCheck(MethodInvocationTree lengthInvocation) { | ||
| Tree parent = lengthInvocation.parent(); | ||
| while (parent.is(Tree.Kind.PARENTHESIZED_EXPRESSION)) { | ||
| parent = parent.parent(); | ||
| } | ||
| if (!(parent instanceof BinaryExpressionTree binaryExpression)) { | ||
| return false; | ||
| } | ||
| ExpressionTree left = ExpressionUtils.skipParentheses(binaryExpression.leftOperand()); | ||
| if (left == lengthInvocation) { | ||
| ExpressionTree right = ExpressionUtils.skipParentheses(binaryExpression.rightOperand()); | ||
| return comparisonWithLiteralOnRight(binaryExpression, right); | ||
| } | ||
| return comparisonWithLiteralOnLeft(binaryExpression, left); | ||
| } | ||
|
|
||
| private static boolean comparisonWithLiteralOnRight(BinaryExpressionTree binaryExpression, ExpressionTree literal) { | ||
| return (binaryExpression.is(Tree.Kind.EQUAL_TO, Tree.Kind.LESS_THAN_OR_EQUAL_TO) && LiteralUtils.isZero(literal)) | ||
| || (binaryExpression.is(Tree.Kind.NOT_EQUAL_TO, Tree.Kind.GREATER_THAN) && LiteralUtils.isZero(literal)) | ||
| || (binaryExpression.is(Tree.Kind.LESS_THAN) && LiteralUtils.isOne(literal)) | ||
| || (binaryExpression.is(Tree.Kind.GREATER_THAN_OR_EQUAL_TO) && LiteralUtils.isOne(literal)); | ||
| } | ||
|
|
||
| private static boolean comparisonWithLiteralOnLeft(BinaryExpressionTree binaryExpression, ExpressionTree literal) { | ||
| return (LiteralUtils.isZero(literal) && binaryExpression.is(Tree.Kind.EQUAL_TO, Tree.Kind.GREATER_THAN_OR_EQUAL_TO)) | ||
| || (LiteralUtils.isZero(literal) && binaryExpression.is(Tree.Kind.NOT_EQUAL_TO, Tree.Kind.LESS_THAN)) | ||
| || (LiteralUtils.isOne(literal) && binaryExpression.is(Tree.Kind.GREATER_THAN)) | ||
| || (LiteralUtils.isOne(literal) && binaryExpression.is(Tree.Kind.LESS_THAN_OR_EQUAL_TO)); | ||
| } | ||
| } | ||
52 changes: 52 additions & 0 deletions
52
java-checks/src/test/java/org/sonar/java/checks/S9432CheckTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| /* | ||
| * SonarQube Java | ||
| * Copyright (C) SonarSource Sàrl | ||
| * mailto:info AT sonarsource DOT com | ||
| * | ||
| * You can redistribute and/or modify this program under the terms of | ||
| * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. | ||
| * | ||
| * This program is distributed in the hope that it will be useful, | ||
| * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | ||
| * See the Sonar Source-Available License for more details. | ||
| * | ||
| * You should have received a copy of the Sonar Source-Available License | ||
| * along with this program; if not, see https://sonarsource.com/license/ssal/ | ||
| */ | ||
| package org.sonar.java.checks; | ||
|
|
||
| import org.junit.jupiter.api.Test; | ||
| import org.sonar.java.checks.verifier.CheckVerifier; | ||
|
|
||
| import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; | ||
|
|
||
| class S9432CheckTest { | ||
|
|
||
| @Test | ||
| void detects_blankness_checks_after_whitespace_removal() { | ||
| CheckVerifier.newVerifier() | ||
| .onFile(mainCodeSourcesPath("checks/S9432CheckSample.java")) | ||
| .withCheck(new S9432Check()) | ||
| .withJavaVersion(11) | ||
| .verifyIssues(); | ||
| } | ||
|
|
||
| @Test | ||
| void ignores_pre_java_11_code() { | ||
| CheckVerifier.newVerifier() | ||
| .onFile(mainCodeSourcesPath("checks/S9432CheckSample.java")) | ||
| .withCheck(new S9432Check()) | ||
| .withJavaVersion(8) | ||
| .verifyNoIssues(); | ||
| } | ||
|
|
||
| @Test | ||
| void ignores_code_without_semantic_information() { | ||
| CheckVerifier.newVerifier() | ||
| .onFile(mainCodeSourcesPath("checks/S9432CheckSample.java")) | ||
| .withCheck(new S9432Check()) | ||
| .withoutSemantic() | ||
| .verifyNoIssues(); | ||
| } | ||
| } |
57 changes: 57 additions & 0 deletions
57
sonar-java-plugin/src/main/resources/org/sonar/l10n/java/rules/java/S9432.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| <p>This rule raises an issue when code calls a method that removes leading and trailing whitespace from a string and then checks its length or | ||
| emptiness to determine if the string contains only whitespace.</p> | ||
| <p>In Java, this specifically refers to the <code>trim()</code> and <code>strip()</code> methods.</p> | ||
| <h2>Why is this an issue?</h2> | ||
| <p>Invoking operations that create new string objects with whitespace removed incurs unnecessary memory allocation and management overhead. When the | ||
| goal is simply to check if a string contains only whitespace, creating this intermediate string object is wasteful.</p> | ||
| <p>The following patterns are inefficient:</p> | ||
| <ul> | ||
| <li>Removing whitespace from a string, then checking if the resulting string has zero length or is empty</li> | ||
| <li>Removing whitespace from a string, then checking if the result contains only whitespace (redundant since the whitespace removal operation | ||
| already eliminates whitespace)</li> | ||
| </ul> | ||
| <p>These checks create a temporary string object just to examine it, which is discarded immediately after the check completes.</p> | ||
| <p>In performance-sensitive code or when processing many strings, this inefficiency can accumulate, increasing memory pressure and CPU usage for | ||
| memory management operations.</p> | ||
| <p>In Java specifically, this applies to patterns like <code>string.trim().length() > 0</code>, <code>string.trim().isEmpty()</code>, | ||
| <code>string.strip().length() > 0</code>, <code>string.strip().isEmpty()</code>, or <code>string.strip().isBlank()</code>.</p> | ||
| <h3>What is the potential impact?</h3> | ||
| <p>The performance impact of this issue depends on how frequently the code executes:</p> | ||
| <ul> | ||
| <li><strong>In tight loops or high-throughput services</strong>: The repeated allocation of temporary String objects can significantly increase | ||
| memory consumption and garbage collection frequency, degrading application performance.</li> | ||
| <li><strong>In typical application code</strong>: The impact is minor but still represents unnecessary overhead that accumulates over the | ||
| application’s lifetime.</li> | ||
| </ul> | ||
| <p>The issue also affects code readability. Using the appropriate whitespace-checking method makes the intent clearer than checking the length of a | ||
| trimmed string.</p> | ||
| <p>In Java, the appropriate method is <code>isBlank()</code>.</p> | ||
| <h2>How to fix it</h2> | ||
| <p>For Java 11 and later, replace trim/strip-based checks with the <code>isBlank()</code> method, which efficiently checks if a string contains only | ||
| whitespace without creating intermediate objects.</p> | ||
| <h3>Code examples</h3> | ||
| <h4>Noncompliant code example</h4> | ||
| <pre data-diff-id="1" data-diff-type="noncompliant"> | ||
| public void validate(String input) { | ||
| if (input != null && input.trim().length() > 0) { // Noncompliant | ||
| process(input); | ||
| } | ||
| } | ||
| </pre> | ||
| <h4>Compliant solution</h4> | ||
| <pre data-diff-id="1" data-diff-type="compliant"> | ||
| public void validate(String input) { | ||
| if (input != null && !input.isBlank()) { | ||
| process(input); | ||
| } | ||
| } | ||
| </pre> | ||
| <h2>Resources</h2> | ||
| <h3>Documentation</h3> | ||
| <ul> | ||
| <li>Java SE Documentation - <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#isBlank()">String (Java SE | ||
| 11 & JDK 11)</a></li> | ||
| <li>Apache Commons Lang Documentation - <a | ||
| href="https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#isBlank-java.lang.CharSequence-">StringUtils</a></li> | ||
| </ul> | ||
|
|
25 changes: 25 additions & 0 deletions
25
sonar-java-plugin/src/main/resources/org/sonar/l10n/java/rules/java/S9432.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| { | ||
| "title": "Strings should not be trimmed or stripped just to check if they are blank", | ||
| "type": "CODE_SMELL", | ||
| "status": "ready", | ||
| "remediation": { | ||
| "func": "Constant\/Issue", | ||
| "constantCost": "5min" | ||
| }, | ||
| "tags": [ | ||
| "performance", | ||
| "optimization", | ||
| "pitfall" | ||
| ], | ||
| "defaultSeverity": "Minor", | ||
| "ruleSpecification": "RSPEC-9432", | ||
| "sqKey": "S9432", | ||
| "scope": "Main", | ||
| "quickfix": "unknown", | ||
| "code": { | ||
| "impacts": { | ||
| "MAINTAINABILITY": "LOW" | ||
| }, | ||
| "attribute": "EFFICIENT" | ||
| } | ||
| } |
Empty file.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.