Feliks
Feliks

Reputation: 21

How to resolve the "Make field an instance variable" issue?

SonarQube 5.5 (with the sonar-java-plugin-3.13.1.jar plugin) reports an issue on this code:

public class TimeA {
    public static final SimpleDateFormat DATE_FORMATTER;

    static {
        SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        df.setTimeZone(TimeZone.getTimeZone("GMT"));
        DATE_FORMATTER=df;
    }
} 

The error message is Make "DATE_FORMATTER" an instance variable.

How can I avoid this SonarQube issue?

Upvotes: 2

Views: 4670

Answers (1)

Darshan Mehta
Darshan Mehta

Reputation: 30839

In the above class, SonarQube is trying to say that DATE_FORMATTER does not need to be static if it is not used by any static method.

In fact, SimpleDateFormat should not be an instance variable as well, as it's not thread safe (explained here). If multiple threads are accessing methods of TimeA class simultaneously then it will lead to incorrect result.

If the format is same then you can declare it as a final String and create SimpleDateFormat instances locally, e.g.:

public final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";

public void someMethod(){
    SimpleDateFormat df=new SimpleDateFormat(DATE_FORMAT);
    df.setTimeZone(TimeZone.getTimeZone("GMT"));
    //Further processing
}

Upvotes: 7

Related Questions