Class TrailingCommentCheck

  • All Implemented Interfaces:
    Configurable, Contextualizable

    public class TrailingCommentCheck
    extends AbstractCheck

    The check to ensure that lines with code do not end with comment. For the case of // comments that means that the only thing that should precede it is whitespace. It doesn't check comments if they do not end a line; for example, it accepts the following: Thread.sleep( 10 /*some comment here*/ ); Format property is intended to deal with the } // while example.

    Rationale: Steve McConnell in Code Complete suggests that endline comments are a bad practice. An end line comment would be one that is on the same line as actual code. For example:

     a = b + c;      // Some insightful comment
     d = e / f;        // Another comment for this line
     

    Quoting Code Complete for the justification:

    • "The comments have to be aligned so that they do not interfere with the visual structure of the code. If you don't align them neatly, they'll make your listing look like it's been through a washing machine."
    • "Endline comments tend to be hard to format...It takes time to align them. Such time is not spent learning more about the code; it's dedicated solely to the tedious task of pressing the spacebar or tab key."
    • "Endline comments are also hard to maintain. If the code on any line containing an endline comment grows, it bumps the comment farther out, and all the other endline comments will have to bumped out to match. Styles that are hard to maintain aren't maintained...."
    • "Endline comments also tend to be cryptic. The right side of the line doesn't offer much room and the desire to keep the comment on one line means the comment must be short. Work then goes into making the line as short as possible instead of as clear as possible. The comment usually ends up as cryptic as possible...."
    • "A systemic problem with endline comments is that it's hard to write a meaningful comment for one line of code. Most endline comments just repeat the line of code, which hurts more than it helps."

    McConnell's comments on being hard to maintain when the size of the line changes are even more important in the age of automated refactorings.

    • Property format - Specify pattern for strings allowed before the comment. Type is java.util.regex.Pattern. Default value is "^[\s});]*$".
    • Property legalComment - Define pattern for text allowed in trailing comments. This pattern will not be applied to multiline comments. Type is java.util.regex.Pattern. Default value is null.

    To configure the check:

     <module name="TrailingComment"/>
     

    Example:

     // OK
     if (/* OK */ x > 5) {}
     int a = 5; // violation
     doSomething(
       param1
     ); // OK, by default such trailing of method/code-block ending is allowed
     

    To configure the check to enforce only comment on a line:

     <module name="TrailingComment">
       <property name="format" value="^\s*$"/>
     </module>
     

    Example:

     // OK
     if (/* OK, this comment does not end the line */ x > 5) {}
     int a = 5; // violation, line content before comment should match pattern "^\s*$"
     doSomething(
       param1
     ); // violation, line content before comment should match pattern "^\s*$"
     

    To configure check so that trailing comment with exact comments like "SUPPRESS CHECKSTYLE", "NOPMD", "NOSONAR" are suppressed:

     <module name="TrailingComment"/>
     <module name="SuppressionXpathSingleFilter">
       <property name="checks" value="TrailingCommentCheck"/>
       <property name="query" value="//SINGLE_LINE_COMMENT
           [./COMMENT_CONTENT[@text=' NOSONAR\n' or @text=' NOPMD\n'
           or @text=' SUPPRESS CHECKSTYLE\n']]"/>
     </module>
     

    Example for trailing comments check to suppress specific trailing comment:

     public class Test {
       int a; // SUPPRESS CHECKSTYLE
       int b; // NOPMD
       int c; // NOSONAR
       int d; // violation, not suppressed
     }
     

    To configure check so that trailing comment starting with "SUPPRESS CHECKSTYLE", "NOPMD", "NOSONAR" are suppressed:

     <module name="TrailingComment"/> <module name="SuppressionXpathSingleFilter">
     <property name="checks" value="TrailingCommentCheck"/>
       <property name="query" value="//SINGLE_LINE_COMMENT
           [./COMMENT_CONTENT[starts-with(@text, ' NOPMD')]]"/>
       <property name="query" value="//SINGLE_LINE_COMMENT
           [./COMMENT_CONTENT[starts-with(@text, ' SUPPRESS CHECKSTYLE')]]"/>
       <property name="query" value="//SINGLE_LINE_COMMENT
           [./COMMENT_CONTENT[starts-with(@text, ' NOSONAR')]]"/>
     </module>
     

    Example:

     public class Test {
       int a; // SUPPRESS CHECKSTYLE - OK, comment starts with " SUPPRESS CHECKSTYLE"
       int b; // NOPMD - OK, comment starts with " NOPMD"
       int c; // NOSONAR - OK, comment starts with " NOSONAR"
       int d; // violation, not suppressed
     }
     

    Parent is com.puppycrawl.tools.checkstyle.TreeWalker

    Violation Message Keys:

    • trailing.comments
    Since:
    3.4
    • Field Detail

      • FORMAT_LINE

        private static final Pattern FORMAT_LINE
        Specify pattern for strings to be formatted without comment specifiers.
      • legalComment

        private Pattern legalComment
        Define pattern for text allowed in trailing comments. This pattern will not be applied to multiline comments.
      • format

        private Pattern format
        Specify pattern for strings allowed before the comment.
    • Method Detail

      • setLegalComment

        public void setLegalComment​(Pattern legalComment)
        Setter to define pattern for text allowed in trailing comments. This pattern will not be applied to multiline comments.
        Parameters:
        legalComment - pattern to set.
      • setFormat

        public final void setFormat​(Pattern pattern)
        Setter to specify pattern for strings allowed before the comment.
        Parameters:
        pattern - a pattern
      • getAcceptableTokens

        public int[] getAcceptableTokens()
        Description copied from class: AbstractCheck
        The configurable token set. Used to protect Checks against malicious users who specify an unacceptable token set in the configuration file. The default implementation returns the check's default tokens.
        Specified by:
        getAcceptableTokens in class AbstractCheck
        Returns:
        the token set this check is designed for.
        See Also:
        TokenTypes
      • checkSingleLineComment

        private void checkSingleLineComment​(DetailAST ast)
        Checks if single-line comment is legal.
        Parameters:
        ast - Detail ast element to be checked.
      • checkBlockComment

        private void checkBlockComment​(DetailAST ast)
        Method to check if block comment is in correct format.
        Parameters:
        ast - Detail ast element to be checked.
      • isLegalCommentContent

        private boolean isLegalCommentContent​(String commentContent)
        Checks if given comment content is legal.
        Parameters:
        commentContent - comment content to check.
        Returns:
        true if the content is legal.