33

Today I had a discussion with a co-worker about the naming of final fields in Java classes.

In his opionion final fields should also be considered constants since their values won't change after the creation of the instance.

This would lead to the following naming convention for final fields:

public class Foo {
    private static final String BLA_BLA = "bla";

    private final String BAR_BATZ;
    
    ...
}

In my opinion only static final fields should be considered constants while fields which are only final should follow the usual camelCase naming convention.

public class Foo {
    private static final String BLA = "bla";

    private final String barBatz;

    ...
}

Now I'm a bit uncertain since he is a far more experienced programmer than I am, so I'm looking for additional input on this.

Sascha Wolf
  • 441
  • 1
  • 4
  • 6
  • Your examples are not constants; you haven't assigned any values to them at compile time. Ergo, they don't follow the naming conventions for constants. – Robert Harvey Aug 04 '14 at 14:53
  • @RobertHarvey Thanks, you are right. The `...` was meant to symbolise any possible constructor which sets the `final` field, but that's obviously not possible for the `static final` field. – Sascha Wolf Aug 04 '14 at 14:57
  • 1
    @Zeeker you may be interested in the `static { }` blocks which can be used to set static fields within a class once when the class is loaded. Related [Working with static constructor in Java](http://programmers.stackexchange.com/q/228242/40980). –  Aug 04 '14 at 15:01
  • @RobertHarvey I'm familiar with those. But thanks nonetheless. – Sascha Wolf Aug 04 '14 at 15:01
  • That wasn't me. :) – Robert Harvey Aug 04 '14 at 15:02
  • 2
    I would say that since the variable belongs to an instance, it will be different from instance to instance, so it doesn't apply as a constant. I would use camel case. – Florian F Aug 24 '14 at 16:39
  • Frankly, I don't see any good reason to use all uppercase for constants. Why not name all fields the same way? – Reinstate Monica Aug 17 '16 at 17:47

2 Answers2

20

Sun (and now Oracle) maintained a document titled Code Conventions for the Java Programming Language. The last update to this was in '99, but the essence of the style guide line lives on.

Chapter 9 covers naming conventions.

For an identifier type of 'constants':

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.)

The examples given:

static final int MIN_WIDTH = 4;

static final int MAX_WIDTH = 999;

static final int GET_THE_CPU = 1;

In a more recent document - its slipped in there. From Variables (The Java Tutorials > Learning the Java Language > Language Basics:

If the name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word. The names gearRatio and currentGear are prime examples of this convention. If your variable stores a constant value, such as static final int NUM_GEARS = 6, the convention changes slightly, capitalizing every letter and separating subsequent words with the underscore character. By convention, the underscore character is never used elsewhere.

Many static analyzers for Java seek to enforce this. For example checkstyle enforces:

Checks that constant names conform to a format specified by the format property. A constant is a static and final field or an interface/annotation field, except serialVersionUID and serialPersistentFields. The format is a regular expression and defaults to ^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$.


This really boils down to the conventions of the community writing the code... and ideally keeping it the same.

The examples above are given as static final ones which are likely derived from the C conventions for #define - which like C, are replaced in the code during compilation rather than at runtime.

The question that then should be asked is "is this behaving like a constant? or is it behaving like a write once field?" - and then following the conventions accordingly. The litmus test for such a question would be "If you were to serialize the object, would you include the final field?" If the answer is that it is a constant then treat it as such (and don't serialize it). On the other hand, if it is part of the state of the object that would need to be serialized, then it isn't a constant.

Whatever the case, it is important to stick with the code style however right or wrong it is. Worse problems erupt from inconsistent conventions within a project than merely something that offends the eye. Consider getting some static analysis tools and configure them to maintain consistency.

  • http://programmers.stackexchange.com/questions/252243/naming-convention-final-fields-not-static#comment506479_252243 – Robert Harvey Aug 04 '14 at 14:54
  • @RobertHarvey I could conceive of some situations where a instance field is behaving like a constant. A Factory, for example, populating something that would otherwise be a constant in the object... though these get to rather contrived examples that hurt my head just thinking about why one would do it. –  Aug 04 '14 at 14:57
  • Thanks for this detailed answer. The litmus test about the serialization of the object made the deal for me. – Sascha Wolf Aug 04 '14 at 15:00
  • A colleague made the valid point recently of saying that, once upon a time, editors weren't very good at highlighting static/static finals etc, so this naming convention was important. These days IDEs are pretty good, so we can maybe make nicer looking names for them, eg: `MinWidth` instead of `MIN_WIDTH`. Another question is: what about static final loggers? Do you call them `LOG`/`LOGGER` or `log`/`logger`. Personally, `log` looks better inline with code, but when is inconsistency acceptable, if at all? – ndtreviv Jun 21 '18 at 12:32
  • @SaschaWolf I'm struggling with this question now myself. To my mind whenever a value is constant, I would want that to look different, e.g. all caps name. I've seen people bring up "well what if it's an object with mutable state?" For me, a reference that can't change is still a constant pointer at an address in memory, a number, so if the place we point to won't change, then the variable is a constant and should be capitalized. For me, I think it boils down to "if the value won't change, make it obvious by putting the name in all caps". But it's still a tough question for some reason... – Ungeheuer Oct 01 '20 at 22:59
  • 3
    Since OP explicitly said "not static", the citations in this answer are largely irrelevant. A final instance field _is part of the state of that object_ and should be camelCase. – user949300 Mar 02 '21 at 08:04
11

BAR_BATZ isn't a constant in this example. The constructors of Foo can set it to different values at the object level. For example

public class Foo {
    private final String BAR_BATZ;

    Foo() {
       BAR_BATZ = "ascending";
    } 

    Foo(String barBatz) {
       BAR_BATZ = barBatz;
    }
}
Kirby
  • 271
  • 2
  • 8