Search code examples
javasonarqubejavadocsquidrule

Sonar javadoc rule


Currently I'm rewriting checkstyle rule JavadocStyle using Sonar internal libraries. But I'm facing one problem - rule throws true on noMainDescription() even if method or class does not have javadoc. I am using sonar javadoc class to get javadoc information. This is my test class:

SonarLint shows which class or method violates rule

This is what I get in sonar:

SonarQube view

One of my tasks is to check if javadoc contains description or is empty and throw violation.

I use this code to check it:

@Override
public void visitNode(Tree tree) {
    Javadoc javadoc = new Javadoc(tree);
    String lines = String.join("  ", javadoc.javadocLines);

    // Javadoc description
    reportEmptyDescription(tree, javadoc);

}

public void reportEmptyDescription(Tree tree, Javadoc javadoc) {
    if (isDescriptionEmpty(javadoc)) {
        reportIssue(tree.firstToken(), "Javadoc has empty description section");
    }
    if (tree.is(Tree.Kind.METHOD) && ((MethodTree) tree).symbol().returnType().toString() != "void"
            && isReturnDescriptionEmpty(javadoc)) {
        reportIssue(tree.firstToken(), "Javadoc has empty return description");
    }
    if (tree.is(Tree.Kind.METHOD) && !((MethodTree) tree).parameters().isEmpty()
            && isParametersDescriptionEmpty(javadoc)) {
        reportIssue(tree.firstToken(), "Javadoc has empty parameters description");
    }
}

public boolean isDescriptionEmpty(Javadoc javadoc) {
    return javadoc.noMainDescription(); // check if it returns true when description exists
}

public boolean isReturnDescriptionEmpty(Javadoc javadoc) {
    return javadoc.noReturnDescription(); // check if it returns true when description exists
}

public boolean isParametersDescriptionEmpty(Javadoc javadoc) {
    if (javadoc.undocumentedParameters().isEmpty()) {
        return false;
    } else {
        return true;
    }
}

My problem is shown in first violation: class does not have javadocs but rule reads that it have but with no description.

Is there a way to prevent this problem?


Solution

  • I have found the problem. It came from this line:

    String lines = String.join("  ", javadoc.javadocLines);
    

    When class or method does not have any javadoc javadoc.javadocLines would return nothing. But String.join still would add space to String lines variable. After rule checks if there is something in lines variable and founds space rule thinks that there is javadoc and it is empty.