简体   繁体   中英

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

When defining a variable of a type of one of the Atomic… classes , and marking it final to avoid replacement, is such a variable considered to be a constant?

The object reference contained in the named variable will not change, because of the final . Yet the Atomic… object is really just a protective wrapper around a payload, a value that may well be changing.

The point of my question is the Java naming conventions. By convention, constants such as a final member field or final static should be named in all-uppercase. So I came to wonder about how to name the object reference of a Atomic… such as AtomicInteger .

Here is a contrived example class.

➥ Should the final private AtomicInteger be named count or COUNT ?

package work.basil.example;

import java.util.concurrent.atomic.AtomicInteger;

public class CountUp
{
    final private AtomicInteger count;  // 🡄 `count` or `COUNT` ?

    public CountUp ( )
    {
        this.count = new AtomicInteger();
    }

    public int increment ( )
    {
        return this.count.incrementAndGet();
    }

    public int getCount ( )
    {
        return this.count.get();
    }
}

You might think this Question of duplicate of ones such as Should a “static final Logger” be declared in UPPER-CASE? or Should I use upper-case naming to declare java constant variables? . But no. I believe the nature of Atomic… objects puts a spin on the issue.

My first thought is: Context is everything. In conversation regarding specifically thread-safety issues, I would refer to the AtomicInteger as a constant. But in the context of the business logic, the payload of the Atomic is meant to be changing. I would not consider an Atomic to be effectively a constant. So I lean to naming with the usual camelCase .

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>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM