Java Conventions – Naming Final/Constant Local Variables in UPPER_SNAKE_CASE

conventionsjava

Pretty simple, I have a method:

public final void myMethod(User user, Group group) {
    final int MAX_USERS_PER_GROUP = group.getMaxUsersPerGroup();
    int usersInGroup = 0;

    // Get users in group and all subgroups, recursively

    if (usersInGroup > MAX_USERS_PER_GROUP) {
        throw new Exception(...);
    }
}

But according to Eclipse:

This name is discouraged. According to convention, names of local variables should start with a lowercase letter.

My worry is that this will get flagged as bad code, even thought it is by all accounts a constant and should be formatted as such.

Best Answer

The code and naming conventions for Java are fairly well established. In particular, this one (or its mismatch) can be seen in Section 9 - Naming Conventions

The names of variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores ("_"). (ANSI constants should be avoided, for ease of debugging.)

static final int MIN_WIDTH = 4;
static final int MAX_WIDTH = 999;
static final int GET_THE_CPU = 1;

The key point is that this is a variable in the example code. Its one that you've given the hint to other coders that once assigned it can't be changed - but it is not a constant. Furthemore, it isn't a class constant.

public final void myMethod(User user, Group group) {
    final int MAX_USERS_PER_GROUP = group.getMaxUsersPerGroup();
    int usersInGroup = 0;

    // Get users in group and all subgroups, recursively

    if (usersInGroup > MAX_USERS_PER_GROUP) {
        throw new Exception(...);
    }
}

This would be incorrect according to the naming standards.

You may wish to look into running checkstyle. The naming conventions checks for this are in accordance with Java naming conventions.

The local final variable check is:

LocalFinalVariableName
    local, final variables, including catch parameters
    ^[a-z][a-zA-Z0-9]*$

It starts with a lower case and does not include underscores. Of course, your team could vary from this Java standard, and tweak checkstyle's rules to make sure that you are all following the same convention - though you will confuse other Java coders who look at the code.