Search code examples
javafinalconventions

Coding conventions: final class instance in CAPITAL_LETTERS?


Constants (final) of primitive types should be written in CAPITAL_LETTERS. But what about a class instance? For example, when it is passed as a function parameter, is called from inner class and should be declared final. Are all parameters supposed to be final? Should it be this way then:

public static void myFunction(
    final MyClass CLASS_INSTANCE) {

    // Code.
}

Solution

  • No, final parameters should not be written in all-uppercase -- they're not constants.

    The terms constant and final are not synonymous.

    Uppercase is indeed used for constants, as specified by early Java naming conventions.

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

    But not all variables declared final are constants. From the Java language specification, section 4.12.4, "Final variables":

    A constant variable is a final variable of primitive type or type String that is initialized with a constant expression (§15.28).

    Parameters are not constants. They're not initialized with a constant expression. And in your example, the parameter is not a primitive type or String.

    Therefore, parameters are specified in mixed case, with an initial lowercase first letter.