-
Hey, I try to write some rules that would detect unused classes, methods and fields in a Spring Application. I already found some examples on GitHub, but it doesn't work for me. For instance to find unused methods I have this code:
but unfortunately it searches for getters & setters and enum methods such as values() and valueOf(), and I am not sure how to avoid that. As for the fields I use this code:
but it detects fields that are used within the same class in some specific method. The method should find all fields that are not used anywhere, but are only declared. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 8 replies
-
Ah, it seems that you already know timtebeek/archunit-unreferenced... 😉
If you want to allow for unused getters & setters, you could probably exclude them explicitly in your // ...
.and(not(rawParameterTypes(/* none */).and(nameStartingWith("get"))))
// ... with a predicate like this: static DescribedPredicate<JavaCodeUnit> rawParameterTypes(Class<?>... expectedTypes) {
return describe("parameters", codeUnit -> {
List<JavaClass> parameterTypes = codeUnit.getRawParameterTypes();
if (parameterTypes.size() != expectedTypes.length) {
return false;
}
for (int i = 0; i < expectedTypes.length; i++) {
if (!parameterTypes.get(i).isEquivalentTo(expectedTypes[i])) {
return false;
}
}
return true;
});
}
You can likewise exclude them by adding // ...
.and(not(rawParameterTypes(String.class).and(name("valueOf")).and(declaredIn(assignableTo(Enum.class))))
.and(not(rawParameterTypes(/* none */).and(name("values")).and(declaredIn(assignableTo(Enum.class))))))
// ... All of those checks can be made more specific by also checking the return parameter type, but this might already give you an idea. |
Beta Was this translation helpful? Give feedback.
-
However, I see one limitation with this. It will still find methods that have been named manually and not automatically generated by the IDE. Let's say someone has a boolean field |
Beta Was this translation helpful? Give feedback.
Ah, it seems that you already know timtebeek/archunit-unreferenced... 😉
If you want to allow for unused getters & setters, you could probably exclude them explicitly in your
methods().that
selection, e.g. for getters:with a predicate like this: