PatternVariableName

Since Checkstyle 8.36

Description

Checks that pattern variable names conform to a specified pattern.

Properties

name description type default value since
format Specifies valid identifiers. Pattern "^[a-z][a-zA-Z0-9]*$" 8.36

Examples

To configure the check:

<module name="Checker">
  <module name="TreeWalker">
    <module name="PatternVariableName"/>
  </module>
</module>
        

Code Example:

class MyClass {
    MyClass(Object o1){
        if (o1 instanceof String STRING) { // violation, name 'STRING' must
        // match pattern '^[a-z][a-zA-Z0-9]*$'
        }
        if (o1 instanceof Integer num) { // OK
        }
    }
}
        

An example of how to configure the check for names that have a lower case letter, followed by letters and digits, optionally separated by underscore:

<module name="Checker">
  <module name="TreeWalker">
    <module name="PatternVariableName">
        <property name="format" value="^[a-z](_?[a-zA-Z0-9]+)*$"/>
    </module>
  </module>
</module>
        

Code Example:

class MyClass {
    MyClass(Object o1){
        if (o1 instanceof String STR) { // violation, name 'STR' must
        // match pattern '^[a-z](_?[a-zA-Z0-9]+)*$'
        }
        if (o1 instanceof Integer num) { // OK
        }
        if (o1 instanceof Integer num_1) { // OK
        }
    }
}
        

An example of how to configure the check to that all variables have 3 or more chars in name:

<module name="Checker">
  <module name="TreeWalker">
    <module name="PatternVariableName">
        <property name="format" value="^[a-z][_a-zA-Z0-9]{2,}$"/>
    </module>
  </module>
</module>
        

Code Example:

class MyClass {
    MyClass(Object o1){
        if (o1 instanceof String s) { // violation, name 's' must
        // match pattern '^[a-z][_a-zA-Z0-9]{2,}$'
        }
        if (o1 instanceof Integer num) { // OK
        }
    }
}
        

Example of Usage

Violation Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.naming

Parent Module

TreeWalker