Skip to content

Commit

Permalink
Allow removal of unused local variables with side effects in initiali…
Browse files Browse the repository at this point in the history
  • Loading branch information
timtebeek authored Oct 23, 2024
1 parent b19a745 commit 75f9cc5
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@ public class RemoveUnusedLocalVariables extends Recipe {
example = "[unused, notUsed, IGNORE_ME]")
String @Nullable [] ignoreVariablesNamed;

@Option(displayName = "Remove unused local variables with side effects in initializer",
description = "Whether to remove unused local variables despite side effects in the initializer. Default false.",
required = false)
@Nullable
Boolean withSideEffects;

@Override
public String getDisplayName() {
return "Remove unused local variables";
Expand Down Expand Up @@ -177,7 +183,9 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation methodInvocat
if (SAFE_GETTER_METHODS.matches(methodInvocation)) {
return methodInvocation;
}
result.set(true);
if (withSideEffects == null || Boolean.FALSE.equals(withSideEffects)) {
result.set(true);
}
return methodInvocation;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ class RemoveUnusedLocalVariablesTest implements RewriteTest {

@Override
public void defaults(RecipeSpec spec) {
spec.recipe(new RemoveUnusedLocalVariables(new String[0]));
spec.recipe(new RemoveUnusedLocalVariables(new String[0], null));
}

@Test
Expand All @@ -73,18 +73,21 @@ static int method(int x) {
@SuppressWarnings("MethodMayBeStatic")
void ignoreVariablesNamed() {
rewriteRun(
spec -> spec.recipe(new RemoveUnusedLocalVariables(new String[]{"unused", "ignoreMe"})),
spec -> spec.recipe(new RemoveUnusedLocalVariables(new String[]{"unused"}, null)),
//language=java
java(
"""
class Test {
void method(Object someData) {
int unused = writeDataToTheDB(someData);
int ignoreMe = writeDataToTheDB(someData);
int unused = 123;
int removed = 123;
}
int writeDataToTheDB(Object save) {
return 1;
}
""",
"""
class Test {
void method(Object someData) {
int unused = 123;
}
}
"""
Expand Down Expand Up @@ -1066,6 +1069,32 @@ static void method() {
);
}

@Test
@Issue("https://github.com/openrewrite/rewrite-feature-flags/pull/35")
void removeDespiteSideEffects() {
rewriteRun(
spec -> spec.recipe(new RemoveUnusedLocalVariables(null, true)),
//language=java
java(
"""
class Test {
int sideEffect() { return 123; }
void method(Object someData) {
int unused = sideEffect();
}
}
""",
"""
class Test {
int sideEffect() { return 123; }
void method(Object someData) {
}
}
"""
)
);
}

@Nested
class Kotlin {

Expand Down

0 comments on commit 75f9cc5

Please sign in to comment.