Skip to content

Commit

Permalink
fix(S1068): delete field writes as well (#917)
Browse files Browse the repository at this point in the history
* Introduce failing test cases

* Remove field writes if they are not read

* Indicate noncompliance
  • Loading branch information
algomaster99 authored Oct 20, 2022
1 parent a0fbddc commit c67cbd8
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -1,12 +1,29 @@
package sorald.processor;

import java.util.List;
import sorald.annotations.ProcessorAnnotation;
import spoon.reflect.code.CtFieldWrite;
import spoon.reflect.code.CtStatement;
import spoon.reflect.declaration.CtClass;
import spoon.reflect.declaration.CtField;
import spoon.reflect.visitor.filter.TypeFilter;

@ProcessorAnnotation(key = "S1068", description = "Unused \"private\" fields should be removed")
public class UnusedPrivateFieldProcessor extends SoraldAbstractProcessor<CtField<?>> {
@Override
protected void repairInternal(CtField<?> element) {
removeAllUnusedPrivateFieldWrites(element);
element.delete();
}

/** Removes all writes to the given field that are not read anywhere. */
private static void removeAllUnusedPrivateFieldWrites(CtField<?> field) {
CtClass<?> parentClass = field.getParent(CtClass.class);
List<CtFieldWrite<?>> unusedFieldWrites =
parentClass.filterChildren(new TypeFilter<>(CtFieldWrite.class)).list();
for (CtFieldWrite<?> unusedFieldWrite : unusedFieldWrites) {
CtStatement statement = unusedFieldWrite.getParent(CtStatement.class);
statement.delete();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
public class PrivateFieldWrittenButNotRead {
private int x; // Noncompliant

private String foo; // Noncompliant

public PrivateFieldWrittenButNotRead(int x, int y) {
this.x = x + y;
}

public void initialize(String bar) {
foo = bar;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
public class PrivateFieldWrittenButNotRead {

public PrivateFieldWrittenButNotRead(int x, int y) { }

public void initialize(String bar) { }
}

0 comments on commit c67cbd8

Please sign in to comment.