forked from phoedos/pmd
java: ImmutableFieldRule - use enum
This commit is contained in:
@@ -33,9 +33,14 @@ import net.sourceforge.pmd.lang.symboltable.NameOccurrence;
|
||||
*/
|
||||
public class ImmutableFieldRule extends AbstractJavaRule {
|
||||
|
||||
private static final int MUTABLE = 0;
|
||||
private static final int IMMUTABLE = 1;
|
||||
private static final int CHECKDECL = 2;
|
||||
private enum FieldImmutabilityType {
|
||||
/** Variable is changed in methods and/or in lambdas */
|
||||
MUTABLE,
|
||||
/** Variable is not changed outside the constructor. */
|
||||
IMMUTABLE,
|
||||
/** Variable is only written during declaration, if at all. */
|
||||
CHECKDECL;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
|
||||
@@ -48,11 +53,11 @@ public class ImmutableFieldRule extends AbstractJavaRule {
|
||||
continue;
|
||||
}
|
||||
|
||||
int result = initializedInConstructor(entry.getValue(), new HashSet<>(constructors));
|
||||
if (result == MUTABLE) {
|
||||
FieldImmutabilityType result = initializedInConstructor(entry.getValue(), new HashSet<>(constructors));
|
||||
if (result == FieldImmutabilityType.MUTABLE) {
|
||||
continue;
|
||||
}
|
||||
if (result == IMMUTABLE || result == CHECKDECL && initializedWhenDeclared(field)) {
|
||||
if (result == FieldImmutabilityType.IMMUTABLE || result == FieldImmutabilityType.CHECKDECL && initializedWhenDeclared(field)) {
|
||||
addViolation(data, field.getNode(), field.getImage());
|
||||
}
|
||||
}
|
||||
@@ -63,8 +68,8 @@ public class ImmutableFieldRule extends AbstractJavaRule {
|
||||
return ((Node)field.getAccessNodeParent()).hasDescendantOfType(ASTVariableInitializer.class);
|
||||
}
|
||||
|
||||
private int initializedInConstructor(List<NameOccurrence> usages, Set<ASTConstructorDeclaration> allConstructors) {
|
||||
int result = MUTABLE;
|
||||
private FieldImmutabilityType initializedInConstructor(List<NameOccurrence> usages, Set<ASTConstructorDeclaration> allConstructors) {
|
||||
FieldImmutabilityType result = FieldImmutabilityType.MUTABLE;
|
||||
int methodInitCount = 0;
|
||||
int lambdaUsage = 0;
|
||||
Set<Node> consSet = new HashSet<>();
|
||||
@@ -98,11 +103,11 @@ public class ImmutableFieldRule extends AbstractJavaRule {
|
||||
}
|
||||
}
|
||||
if (usages.isEmpty() || methodInitCount == 0 && lambdaUsage == 0 && consSet.isEmpty()) {
|
||||
result = CHECKDECL;
|
||||
result = FieldImmutabilityType.CHECKDECL;
|
||||
} else {
|
||||
allConstructors.removeAll(consSet);
|
||||
if (allConstructors.isEmpty() && methodInitCount == 0 && lambdaUsage == 0) {
|
||||
result = IMMUTABLE;
|
||||
result = FieldImmutabilityType.IMMUTABLE;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
|
Reference in New Issue
Block a user