gatinueta gatinueta - 22 days ago 11
Java Question

Naming of method-local constants in checkstyle

How should java method-local constants be named?

If a constant is used only used in the context of a method, it should be declared inside the method (as a

final
variable). But what syntax should be used? For me, the most readable way is to use
ALL_CAPS
, but checkstyle seems to disagree:

int compute(int n) {
final int FACTOR = 27;
return FACTOR * n;
}


will produce the checkstyle warning:

Name 'FACTOR' must match pattern '^[a-z][a-zA-Z0-9]*$'.


See also: What are your thoughts on method scoped constants?

Answer

Google Java Style, the currently popular style guide, says:

Local variable names are written in lowerCamelCase [...] Even when final and immutable, local variables are not considered to be constants, and should not be styled as constants.

This is also the convention assumed by Checkstyle's LocalFinalVariableName check.

Comments