Constants should be named consistently to communicate intent and improve maintainability. Rename your constants to follow your project’s naming convention to address this issue.

Why is this an issue?

Constants are variables whose value does not change during the runtime of a program after initialization. Oftentimes, constants are used in multiple locations across different subroutines.

It is important that the names of constants follow a consistent and easily recognizable pattern. This way, readers immediately understand that the referenced value does not change, which simplifies debugging.

Or, in the case of primitive constants, that accessing the constant is thread-safe.

This rule checks that all constant names match a given regular expression.

What is the potential impact?

Ignoring the naming convention for constants makes the code less readable since constants and variables are harder to tell apart. Code that is hard to understand is also difficult to maintain between different team members.

How to fix it

First, familiarize yourself with the particular naming convention of the project in question. Then, update the name of the constant to match the convention, as well as all usages of the name. For many IDEs, you can use built-in renaming and refactoring features to update all usages of a constant at once.

Code examples

Noncompliant code example

The following example assumes that constant names should match the default regular expression ^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$:

public class MyClass {
  public static final float pi = 3.14159f; // Noncompliant: Constant is not capitalized

  void myMethod() {
    System.out.println(pi);
  }
}

public enum MyEnum {
  optionOne, // Noncompliant
  optionTwo; // Noncompliant
}

Compliant solution

public class MyClass {
  public static final float PI = 3.14159f;

  void myMethod() {
    System.out.println(PI);
  }
}

public enum MyEnum {
  OPTION_ONE,
  OPTION_TWO;
}

Resources

External coding guidelines