Skip to content

Commit

Permalink
fix: 🩹 "++i" statement is not so bad
Browse files Browse the repository at this point in the history
In some cases, postfix increment may be intentional.

Closes #4
  • Loading branch information
pataluc committed May 29, 2024
1 parent ee04ea3 commit 59c50bc
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ public List<Kind> nodesToVisit() {

@Override
public void visitNode(Tree tree) {
reportIssue(tree, MESSAGERULE);
if (tree.parent().is(Kind.EXPRESSION_STATEMENT)) {
reportIssue(tree, MESSAGERULE);
}
}
}
47 changes: 36 additions & 11 deletions src/test/files/IncrementCheck.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,46 +18,71 @@
class IncrementCheck {
IncrementCheck(IncrementCheck mc) {
}

int foo1() {
int counter = 0;
return counter++; // Noncompliant {{Use ++i instead of i++}}
return counter++; // Compliant but should raise a java:S2123 and a java:S1854
}

private int j = 0;
int foo10() {
return this.j++; // Compliant because maybe the use case needs to return j AND increment it
}

int foo11() {
int counter = 0;
return ++counter;
}

void foo2(int value) {
int foo2() {
int counter = 0;
counter++; // Noncompliant {{Use ++i instead of i++}}
return counter;
}

void foo22(int value) {
int foo22() {
int counter = 0;
++counter;
return counter;
}

void foo3(int value) {
int foo3() {
int counter = 0;
counter = counter + 197845 ;
return counter;
}

void foo4(int value) {
int counter =0;
int foo4() {
int counter = 0;
counter = counter + 35 + 78 ;
return counter;
}

void foo50(int value) {
void foo50() {
for (int i=0; i < 10; i++) { // Noncompliant {{Use ++i instead of i++}}
System.out.println(i);
System.out.println(i); //NOSONAR
}
}

void foo51(int value) {
void foo51() {
for (int i=0; i < 10; ++i) {
System.out.println(i);
System.out.println(i); //NOSONAR
}
}

void bar61(int value) {
// For test purpose
}

int foo61() {
int i = 0;
bar61(i++); // Compliant because maybe bar61 needs the unincremented value
return i;
}

int foo62() {
int i = 0;
bar61(2 + i++); // Compliant because maybe bar61 needs the unincremented value
return i;
}
}

0 comments on commit 59c50bc

Please sign in to comment.