Skyler
Skyler

Reputation: 2864

Custom SonarQube Rule to identify instance variables

I am creating a custom SonarQube rule to warn about instance variables names that contain a particular string. It appears that Kind.VARIABLE detects all variables, including local variables. Is there a way to detect and handle instance variables only?

Upvotes: 1

Views: 487

Answers (1)

Babl
Babl

Reputation: 7646

Why not to check for the Kind of the parent ? For the instance variables it should be a CLASS.

Working Rule which bann's the BLABLAstring in the instance variables will look something like this.

@Rule(key = "Banned Keyword Rule")
public class BannedKeywordRule extends IssuableSubscriptionVisitor {
    // Define the word to ban
    private static final String BANNED_KEYWORD = "BLABLA";

    @Override
    public List<Tree.Kind> nodesToVisit() {
        //  visit only the variables
        return ImmutableList.of(Tree.Kind.VARIABLE);
    }

    @Override
    public void visitNode(Tree tree) {
        VariableTree variableTree = (VariableTree) tree;
        // check if parent is CLASS aka variable is instance
        if(variableTree.parent().is(Tree.Kind.CLASS) && variableTree.simpleName().name().contains(BANNED_KEYWORD)) {
            reportIssue(variableTree, "String " + BANNED_KEYWORD + " can not be used as a instance variable.");
        }
    }
}

Upvotes: 2

Related Questions