9

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.

NobleUplift
  • 815
  • 3
  • 7
  • 16
  • http://meta.programmers.stackexchange.com/questions/6582/on-the-troubles-of-naming-and-terminology – gnat Apr 09 '15 at 15:52
  • 1
    "yes, absolutely, these questions are on-topic, and here's why I think so" I posted a similar question on this Stack Exchange that is +6. I don't see your point. – NobleUplift Apr 09 '15 at 15:55
  • 4
    @gnat this isn't a naming or terminology question. It's a question about code conventions – Alex Apr 09 '15 at 15:58
  • Well, it's half 'n' half. Six in one, half dozen in the other. – NobleUplift Apr 09 '15 at 16:02
  • 1
    @AlexFoxGill "This name is discouraged" vs "it is by all accounts a constant and should be formatted as such" sounds like a question polling for opinions – gnat Apr 09 '15 at 16:12
  • 1
    if(usersInGroup > group.getMaxUsersPerGroup()) { /* ... */ } You should try to avoid defining constants within methods, if at all possible – HotelCalifornia Apr 09 '15 at 18:02
  • Even if MAX_USERS_PER_GROUP is a constant (which is debatable), I would hope myMethod isn't so big that you need a naming convention to keep track of local variables. – Doval Apr 09 '15 at 18:03
  • 2
    I would point out that @HotelCalifornia's approach is the appropriate one in Java. Small methods can get inlined by the JIT to become direct field accesses (this is the meaning behind "small methods are cheap in Java"). It also clearly identifies where the data is coming from without cluttering the method with additional aliases to the data (even if they are final). –  Apr 09 '15 at 21:11
  • The reason I did this is because group.getMaxUsersPerGroup() came from a different database object with a different name, so if I have to revert this code I can change it at one location, not many. @Doval I'd say it's close to 500 lines long. – NobleUplift Apr 10 '15 at 15:21
  • Hmmmmmm, I like how someone from this thread -1'ed my "When comparing floats, what do you call the threshold of difference?" HMMMMMM...... – NobleUplift Apr 10 '15 at 15:30

2 Answers2

15

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.

  • "This would be incorrect according to the naming standards." there are NOT any naming Standard. Since each company/grp has their own StandardS. – Yousha Aleayoub Mar 15 '16 at 20:14
2

Constants are things given values that are known before or during compilation.

What you've declared is a variable because its value is determined at runtime by invoking a method. The fact that it's final is really just a convenience for letting the compiler know that once the value is set, it won't be changed.

Blrfl
  • 20,375
  • I would amend that to be 'at compile time or once, when the class is loaded'. Having final static Something FOO_BAR; static { FOO_BAR = somethingComplex(); ... } would still fall into the class constant, even though it isn't known at compile time. –  Apr 09 '15 at 17:05
  • @MichaelT That seems off to me. Why do static final variables get to be called constants when their value isn't available at compile time but final local variables don't? The intent of the Java conventions seems to be that only static constant variables are capitalized. If they intended otherwise you'd think they would've used one of the three examples to illustrate that. – Doval Apr 09 '15 at 17:38
  • @MichaelT: That case dips its toe into a gray area. Even if it is static, not declaring the variable final means it's mutable and should be named following the convention for variables. I understand the intent, but all that would keep FOO_BAR a constant conceptually is good discipline on the coder's part. (Edit: Doval kinda beat me to it.) – Blrfl Apr 09 '15 at 17:41
  • @Doval let me phrase it this way, all the static analysis tools that I use fuss if I have a static final that isn't all caps snake case. Here's the test for you - how do you name your logger? private static final Logger LOG = Logger.getLogger(MyClass.class); is what I've seen most often. Not everywhere, as you pointed out there is debate on that, but LOG isn't a small minority (and also lots of people special case 'logger' for a valid name of a static final field in checkstyle). –  Apr 09 '15 at 17:45
  • @MichaelT That's fair. In my opinion that still doesn't make LOG a constant and I wouldn't amend Blrfl's definition. I'd just say that making all static final variables ALL_CAPS regardless of whether they're constants is a popular convention, and that this convention doesn't extend to local variables (even constant ones). – Doval Apr 09 '15 at 18:00
  • @Doval this style guide which would make it static final Logger log also has the side effect of static final String someString = "foo"; if you ever do someString.equals(...) which... well, its a style guide for someone. Others equivocate on the immutable nature of the value in the field. In that case it would be LOG because the slf4j logger is immutable... unless you're using log4j which is mutable. The key thing for me for the convention is consistency and simplicity thus static final Logger LOG; –  Apr 09 '15 at 18:06
  • @MichaelT I don't disagree that conventions vary a lot on precisely what should be ALL_CAPS, or that capitalizing every immutable class variable is a sensible convention. I'm just objecting to amending the definition of a constant to include things that are calculated at run time. If you say something is a constant, I expect to be able to use it in a switch statement, and that determining its value can never fail. Wikipedia seems to agree. – Doval Apr 09 '15 at 18:33
  • @Doval but you haven't been able to switch on a String prior to Java 8. Nor would anything but an enumerable primitive could be switched on (you can't switch on a float or double as in Math.PI, Math.E or more complex types such as BigDecimal.TEN... and Color.BLUE isn't an enumerable type, valid for a switch, either). I've got enough trouble with people having inconsistent styles in the code base, thus my preference for simple and consistent. –  Apr 09 '15 at 18:40
  • @MichaelT You can switch on Strings since Java 7. Fair point on floats and doubles, I hadn't realized they can't be used in switches (although I don't see why not, besides them wanting to discourage naive float/double comparisons.) My statement was too narrow, but I stand by my opinion that only those things that are computed at compile time are constants. – Doval Apr 09 '15 at 18:58