Skip to content

Commit

Permalink
fix(S1155): return empty check for collections whose size < 1 (#1026)
Browse files Browse the repository at this point in the history
  • Loading branch information
algomaster99 authored Apr 26, 2023
1 parent f05cbf7 commit 5241e92
Show file tree
Hide file tree
Showing 6 changed files with 47 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,23 @@ protected void repairInternal(CtBinaryOperator<?> element) {
.orElseThrow(IllegalStateException::new);
CtInvocation<?> newInvocation =
getFactory().createInvocation(methodCallTarget, isEmptyMethod.getReference());
CtExpression<?> expression =
element.getKind() == BinaryOperatorKind.EQ ? newInvocation : not(newInvocation);
CtExpression<?> expression = getIsEmptyInvocation(newInvocation, element);
element.replace(expression);
}

/**
* Returns the invocation of isEmpty() that should be used to replace the given element. If the
* operator is == or < 1, then we can just return the invocation, otherwise we need to negate
* it.
*/
private CtExpression<?> getIsEmptyInvocation(
CtInvocation<?> invocation, CtBinaryOperator<?> element) {
if (element.getKind() == BinaryOperatorKind.EQ) {
return invocation;
} else if (element.getKind() == BinaryOperatorKind.LT
&& element.getRightHandOperand().equals(getFactory().createLiteral(1))) {
return invocation;
}
return not(invocation);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,10 @@ Example:
...
- if (myCollection.size() != 0) { // Noncompliant
+ if (!myCollection.isEmpty()) {
...
- if (myCollection.size() < 1) { // Noncompliant
+ if (myCollection.isEmpty()) {
```

> We ignore expressions such as `0 == myCollections.size()` based on heuristics
> that it is not a common practice to do so.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import java.util.Collection;

public class CollectionIsEmpty {
public class EqualTo {
public static void main(String[] args) {
Collection myCollection = null;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import java.util.Collection;

public class CollectionIsEmpty {
public class EqualTo {
public static void main(String[] args) {
Collection myCollection = null;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import java.util.Collection;

public class LessThan {
public static void main(String[] args) {
Collection myCollection = null;

if (myCollection.size() < 1) { // Noncompliant
/* ... */
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import java.util.Collection;

public class LessThan {
public static void main(String[] args) {
Collection myCollection = null;

if (myCollection.isEmpty()) {
/* ... */
}
}
}

0 comments on commit 5241e92

Please sign in to comment.