Should a "Static Final Logger" Be Declared in Upper-Case

Should a static final Logger be declared in UPPER-CASE?

The logger reference is not a constant, but a final reference, and should NOT be in uppercase. A constant VALUE should be in uppercase.

private static final Logger logger = Logger.getLogger(MyClass.class);

private static final double MY_CONSTANT = 0.0;

Should static objects that have methods associated with them be capitalised?

Generally constants are declared in uppercase letters. Again it depends on project preference.
This may be duplicate of thread Java naming convention for static final variables.

Does it make a difference to declare a logger in all uppercase and make it final?

It is a convention inherited from the C/C++ world that constants are named all uppercase. Since in Java, the closest equivalent of constant is static final, these members are often named similarly.

In this case, the distinction may not be so important, since logger objects are semantically not constants. Nevertheless, it is still recommended to declare them static to ensure you have a single instance per class, and you may want to declare them final to ensure that the reference to the object can't be changed later (and to communicate this fact to readers of your code).

Update to @Moncader's comment:

  1. static is equivalent to C++ (class) static - just as well as it does not make much sense in C++ to declare your constants as non-static, it does not make sense in Java either.

  2. final is not a direct equivalent of C++ const. It means that the reference in question can not be changed. However, it does not prevent changing the object referred to! So it only works as const if it protects a primitive value (e.g. int) or a reference to an immutable object (e.g. String). To stay with our current topic, consider

    private static final Logger logger = LoggerFactory.getLogger(Main.class);
    ...
    logger.setLevel(Level.INFO);
    logger.addAppender(...);
    logger.setAdditivity(false);

All of these calls are obviously changing the state of the logger, even though it is declared final. That's what I meant above by stating that logger objects are semantically not constants.

Should I name final `Atomic…` member fields as constants (in all uppercase) per Java conventions?

Google's code style guidelines says that final fields that reference a mutable object are not considered "constants" and are not capitalized.

https://google.github.io/styleguide/javaguide.html

To quote section 5.2.4 Constant names:

But what is a constant, exactly?

Constants are static final fields whose contents are deeply immutable and whose methods have no detectable side effects. This includes primitives, Strings, immutable types, and immutable collections of immutable types. If any of the instance's observable state can change, it is not a constant. Merely intending to never mutate the object is not enough.

Some examples from that section:

// Not constants
static String nonFinal = "non-final";
final String nonStatic = "non-static";
static final Set<String> mutableCollection = new HashSet<String>();

Java naming convention for static final variables

That's still a constant. See the JLS for more information regarding the naming convention for constants. But in reality, it's all a matter of preference.


The names of constants in interface types should be, and final
variables of class types may conventionally be, a sequence of one or
more words, acronyms, or abbreviations, all uppercase, with components
separated by underscore "_" characters. Constant names should be
descriptive and not unnecessarily abbreviated. Conventionally they may
be any appropriate part of speech. Examples of names for constants
include MIN_VALUE, MAX_VALUE, MIN_RADIX, and MAX_RADIX of the
class Character.

A group of constants that represent alternative values of a set, or,
less frequently, masking bits in an integer value, are sometimes
usefully specified with a common acronym as a name prefix, as in:

interface ProcessStates {
int PS_RUNNING = 0;
int PS_SUSPENDED = 1;
}

Obscuring involving constant names is rare:

  • Constant names normally have no lowercase letters, so they will not normally obscure names of packages or types, nor will they normally shadow fields, whose names typically contain at least one lowercase letter.
  • Constant names cannot obscure method names, because they are distinguished syntactically.

Why do we declare Loggers static final?

  • private - so that no other class can hijack your logger
  • static - so there is only one logger instance per class, also avoiding attempts to serialize loggers
  • final - no need to change the logger over the lifetime of the class

Also, I prefer name log to be as simple as possible, yet descriptive.

EDIT: However there is an interesting exception to these rules:

protected final Logger log = LoggerFactory.getLogger(getClass());

as opposed to:

private static final Logger log = LoggerFactory.getLogger(Foo.class);

The former way allows you to use the same logger name (name of the actual class) in all classes throughout the inheritance hierarchy. So if Bar extends Foo, both will log to Bar logger. Some find it more intuitive.

Should be logger always final and static?

All major java logging packages (java.util.logging, log4j, etc.) are synchronized and thread safe. The standard pattern of a private final static logger per class is fine even if the class is called from multiple threads.

Should logger be private static or not

The advantage of the non-static form is that you can declare it in an (abstract) base class like follows without worrying that the right classname will be used:

protected Log log = new Log4JLogger(getClass());

However its disadvantage is obviously that a whole new logger instance will be created for every instance of the class. This may not per se be expensive, but it adds a significant overhead. If you'd like to avoid this, you'd like to use the static form instead. But its disadvantage is in turn that you have to declare it in every individual class and take care in every class that the right classname is been used during logger's construction because getClass() cannot be used in static context. However, in the average IDE you can create an autocomplete template for this. E.g. logger + ctrl+space.

On the other hand, if you obtain the logger by a factory which in turn may cache the already-instantiated loggers, then using the non-static form won't add that much overhead. Log4j for example has a LogManager for this purpose.

protected Log log = LogManager.getLogger(getClass());

Which is the best way to declare logger variable in java

I vote for 3

 private static final Logger LOGGER = Logger.getLogger(ServiceImpl.class);

It's final since you don't change it and it's in uppercase since it's a constant.



Related Topics



Leave a reply



Submit