Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton Java class can have static constant variable ? Sonar lint error

In Java singleton class, I want to make a final constant like below code.

  1. private final int threshold = 3; // Noncompliant Code Example by Sonal lint
  2. private static final int THRESHOLD = 3; // Compliant code by Sonarlint

My question is, why singleton class should have the static keyword in a final int/string constant as this class has only one instance?

like image 311
Ashutoshg Avatar asked Dec 17 '22 20:12

Ashutoshg


2 Answers

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.

like image 142
Mureinik Avatar answered Jan 31 '23 20:01

Mureinik


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.

like image 42
ETO Avatar answered Jan 31 '23 19:01

ETO