From 13d0f9d6504323005f71e721ca0e665f7ac0cba7 Mon Sep 17 00:00:00 2001 From: Knut Wannheden Date: Thu, 19 Jan 2023 22:42:30 +0100 Subject: [PATCH] Fix handling of unary operator in `FinalizePrivateField` (#2679) The recipe should distinguish between reading and modifying unary operators, as this may allow a few more fields to be made final. --- .../cleanup/FinalizePrivateFieldsTest.java | 20 +++++++++++++++++++ .../java/cleanup/FinalizePrivateFields.java | 4 +++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/rewrite-java-test/src/test/java/org/openrewrite/java/cleanup/FinalizePrivateFieldsTest.java b/rewrite-java-test/src/test/java/org/openrewrite/java/cleanup/FinalizePrivateFieldsTest.java index 31184f44e9e..b9de7ff6f63 100644 --- a/rewrite-java-test/src/test/java/org/openrewrite/java/cleanup/FinalizePrivateFieldsTest.java +++ b/rewrite-java-test/src/test/java/org/openrewrite/java/cleanup/FinalizePrivateFieldsTest.java @@ -304,6 +304,26 @@ class A { ); } + @Test + void fieldReferencedByNonModifyingUnaryOperator() { + rewriteRun( + java( + """ + class A { + private int i = 42; + private int j = -i; + } + """, + """ + class A { + private final int i = 42; + private final int j = -i; + } + """ + ) + ); + } + @Disabled ("Doesn't support multiple constructors, to be enhanced") @Test void fieldAssignedInAllAlternateConstructors() { diff --git a/rewrite-java/src/main/java/org/openrewrite/java/cleanup/FinalizePrivateFields.java b/rewrite-java/src/main/java/org/openrewrite/java/cleanup/FinalizePrivateFields.java index 906e91a9b7d..328bd8b5f2e 100644 --- a/rewrite-java/src/main/java/org/openrewrite/java/cleanup/FinalizePrivateFields.java +++ b/rewrite-java/src/main/java/org/openrewrite/java/cleanup/FinalizePrivateFields.java @@ -140,7 +140,9 @@ public J.AssignmentOperation visitAssignmentOperation(J.AssignmentOperation assi @Override public J.Unary visitUnary(J.Unary unary, Map assignedCountMap) { J.Unary u = super.visitUnary(unary, assignedCountMap); - updateAssignmentCount(getCursor(), u.getExpression(),assignedCountMap); + if (u.getOperator().isModifying()) { + updateAssignmentCount(getCursor(), u.getExpression(), assignedCountMap); + } return u; }