简体   繁体   中英

Java Singleton Class Final Variable Naming Convention

I understand that instance-level final variables follow the camel case naming conventions but I was wondering if it should be the case for a Singleton Class as well.

Would you treat final in a Singleton Class as a constant and follow the constants naming convention as follows:

private final SomeObject SOME_OBJECT;

OR, would you name it in camel case, following the normal variable naming conventions?

private final SomeObject someObject;

This keeps on popping up in multiple code reviews and I always have some grey area. Appreciate any thoughts on this.

According to typical Java coding standards and conventions, the ALL_CAPS identifier style is reserved for static final constants (and enum constants ...). In your case, the variable is final but not static , so that exception to the normal rules for variables does not apply.

That is my interpretation, and (I think) the most common interpretation. It is not the only interpretation. You and your team could choose to interpret the conventions differently, or even ignore them entirely 1 .

The most important thing is to be consistent across you / your team / your organization's common code base.


1 - ... though the latter would be unwise , IMO,

This is a topic that is more based on community opinion than on a set standard.

If it is at the class level, and it is final, and there is only one instance, assuming you are using it as a constant, in my opinion, I would use Underscore, as it is basically a constant, but it is initialized at runtime.

class AClass {
    private final SomeObject SOME_OBJECT;
    private initInstance() {
        SOME_OBJECT = ...;
    }
    ...
}

This might be a helpful link: https://softwareengineering.stackexchange.com/questions/252243/naming-convention-final-fields-not-static

What this link boils down to is that while any answer will be opinionated, a good heuristic would be to ask yourself "is this behaving like a constant? or is it behaving like a write once field?"

If it is a constant that is made at runtime, DO_THIS .

If it is a field that you write to once, but manipulate later, doThis .

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