Write to static field from instance method

java, sonarqube

Solution

Not sure how your static analysis tool works but -

try writing to your value via a static setter:

private synchronized static void setDataSource(DataSource ds) {
    dataSource = ds;
}

so that you can do

   if(dataSource == null){
        setDataSource(getDataSource());
   }

Problem

I have my code as below. I see ``` public MyClass{ private static DataSource dataSource = null; private static DataSource getDataSource(){ if (dataSource == null) { try { dataSource = // something. } catch (Exception e) { // some exception. } } return dataSource; } public List doSomething(){ // ... if(dataSource == null){ dataSource = getDataSource(); } dataSource.getConnection(); // ... } } ``` I see following message in sonar anaylsis. ``` Dodgy - Write to static field from instance method This instance method writes to a static field. This is tricky to get correct if multiple instances are being manipulated, and generally bad practice. findbugs:ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD Sep12 Reliability > Architecture ``` I see everything is okay in this implementation except that we are changing the static variable in doSomething method. How do we fix this ?

Original source