LocalFinalVariableName

Since Checkstyle 3.0

Description

Checks that local final variable names conform to a specified pattern. A catch parameter and resources in try statements are considered to be a local, final variables.

Properties

name description type default value since
format Specifies valid identifiers. Pattern "^[a-z][a-zA-Z0-9]*$" 3.0
tokens tokens to check subset of tokens VARIABLE_DEF , PARAMETER_DEF , RESOURCE . VARIABLE_DEF , PARAMETER_DEF , RESOURCE . 3.0

Examples

To configure the check:

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

An example of how to configure the check for names that are only upper case letters and digits is:

<module name="Checker">
  <module name="TreeWalker">
    <module name="LocalFinalVariableName">
      <property name="format" value="^[A-Z][A-Z0-9]*$"/>
    </module>
  </module>
</module>
        

Code Example:

class MyClass {
  void MyMethod() {
    try {
      final int VAR1 = 5; // OK
      final int var1 = 10; // violation,  name 'var1' must match pattern "^[A-Z][A-Z0-9]*$"
    } catch (Exception ex) {
      final int VAR2 = 15; // OK
      final int var2 = 20; // violation,  name 'var2' must match pattern "^[A-Z][A-Z0-9]*$"
    }
  }
}
        

An example of how to configure the check for names of local final parameters and resources in try statements (without checks on variables):

<module name="Checker">
  <module name="TreeWalker">
    <module name="LocalFinalVariableName">
      <property name="format" value="^[A-Z][A-Z0-9]*$"/>
      <property name="tokens" value="PARAMETER_DEF,RESOURCE"/>
    </module>
  </module>
</module>
        

Code Example:

class MyClass {
  void MyMethod() {
    try(Scanner scanner = new Scanner()) { // violation, name 'scanner' must
                                           // match pattern '^[A-Z][A-Z0-9]*$'
      final int VAR1 = 5; // OK
      final int var1 = 10; // OK
    } catch (final Exception ex) { // violation, name 'ex'
                                   // must match pattern '^[A-Z][A-Z0-9]*$'
      final int VAR2 = 15; // OK
      final int var2 = 20; // 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