Skip to content

Commit

Permalink
Make IsEmptyCallOnCollections also support < and > operators
Browse files Browse the repository at this point in the history
The expressions `c.size() > 0` and `0 < c.size()` can both also be replaced with `!c.isEmpty()`.
  • Loading branch information
knutwannheden committed Jan 8, 2023
1 parent cb9654e commit a04fdda
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,10 @@ static void method(List<String> l) {
// empty body
} else if (l.size() != 0 || 0 != l.size()) {
// empty body
} else if (l.size() > 0 || l.size() < 0) {
// empty body
} else if (0 < l.size() || 0 > l.size()) {
// empty body
}
}
}
Expand All @@ -89,6 +93,10 @@ static void method(List<String> l) {
// empty body
} else if (!l.isEmpty() || !l.isEmpty()) {
// empty body
} else if (!l.isEmpty() || l.size() < 0) {
// empty body
} else if (!l.isEmpty() || 0 > l.size()) {
// empty body
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,15 +68,17 @@ public JavaVisitor<ExecutionContext> getVisitor() {

@Override
public J visitBinary(J.Binary binary, ExecutionContext ctx) {
if (binary.getOperator() == J.Binary.Type.Equal || binary.getOperator() == J.Binary.Type.NotEqual) {
if (COLLECTION_SIZE.matches(binary.getLeft()) || COLLECTION_SIZE.matches(binary.getRight())) {
if (isZero(binary.getLeft()) || isZero(binary.getRight())) {
J.MethodInvocation sizeCall = (J.MethodInvocation) (COLLECTION_SIZE.matches(binary.getLeft()) ?
binary.getLeft() : binary.getRight());
if (isZero(binary.getLeft()) || isZero(binary.getRight())) {
boolean zeroRight = isZero(binary.getRight());
J.MethodInvocation maybeSizeCall = (J.MethodInvocation) (zeroRight ? binary.getLeft() : binary.getRight());
if (binary.getOperator() == J.Binary.Type.Equal || binary.getOperator() == J.Binary.Type.NotEqual
|| zeroRight && binary.getOperator() == J.Binary.Type.GreaterThan
|| !zeroRight && binary.getOperator() == J.Binary.Type.LessThan) {
if (COLLECTION_SIZE.matches(maybeSizeCall)) {
String op = binary.getOperator() == J.Binary.Type.Equal ? "" : "!";
return (sizeCall.getSelect() == null ?
sizeCall.withTemplate(isEmptyNoReceiver, sizeCall.getCoordinates().replace(), op) :
sizeCall.withTemplate(isEmpty, sizeCall.getCoordinates().replace(), op, sizeCall.getSelect())
return (maybeSizeCall.getSelect() == null ?
maybeSizeCall.withTemplate(isEmptyNoReceiver, maybeSizeCall.getCoordinates().replace(), op) :
maybeSizeCall.withTemplate(isEmpty, maybeSizeCall.getCoordinates().replace(), op, maybeSizeCall.getSelect())
).withPrefix(binary.getPrefix());
}
}
Expand Down

0 comments on commit a04fdda

Please sign in to comment.