diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ce62a8..cff0625 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- [#4](https://github.com/green-code-initiative/ecoCode-java/issues/4) Improvement: "++i" statement is not so bad + ### Deleted ## [1.6.1] - 2024-05-15 diff --git a/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java b/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java index 00c3094..76b8057 100644 --- a/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java +++ b/src/main/java/fr/greencodeinitiative/java/checks/IncrementCheck.java @@ -39,6 +39,8 @@ public List nodesToVisit() { @Override public void visitNode(Tree tree) { - reportIssue(tree, MESSAGERULE); + if (tree.parent().is(Kind.EXPRESSION_STATEMENT)) { + reportIssue(tree, MESSAGERULE); + } } } diff --git a/src/test/files/IncrementCheck.java b/src/test/files/IncrementCheck.java index 54b20bf..b31ffa8 100644 --- a/src/test/files/IncrementCheck.java +++ b/src/test/files/IncrementCheck.java @@ -15,13 +15,18 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -class MyClass { - MyClass(MyClass mc) { +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() { @@ -29,35 +34,55 @@ int foo11() { 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; + } } \ No newline at end of file