In Java singleton class, I want to make a final constant like below code.
private final int threshold = 3;
// Noncompliant Code Example by Sonal lintprivate static final int THRESHOLD = 3;
// Compliant code by SonarlintMy question is, why singleton class should have the static
keyword in a final
int
/string
constant as this class has only one instance?
This is probably a caveat that Sonar Lint can't recognize. It's pretty hard to recognize a singleton with static analysis, so they just opted to ignore this caveat and issue a warning anyway.
While theoretically you're right (there's just one instance, so the constant will be declared only once anyway), you may be better off saving future maintainers of this code the confusion (and the need to configure Sonar to ignore this warning), and just define it as static
too. You also may gain a minute memory consumption improvement if the compiler actually inlines it, which AFAIK, it only does with static final
members.
This is an ordinary declaration of a constant in java.
private static final int THRESHOLD = 3;
It means that all the instances of your class will access the same field.
When you declare it like private final int THRESHOLD = 3;
this means that every instance of your class will have its own copy of THRESHOLD
field. It does not make any sense to declare it non-static when you immediately initialize it:
private final int THRESHOLD = 3;
Declaring non-static final fields makes sense when you initialize them in constructor. Thus all the instances have the same constant field with different values:
private final int threshold;
protected YourConstructor(int threshold){
this.threshold = threshold;
}
Just follow Sonarlint's advice and declare it as a static
constant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With