[java:S2095] Initializing Closeable before return

Non-immediately returning newly created Closeable should not be reported as java:S2095.

I am using SonarLint 5.7 with Eclipse.

import java.io.Closeable;
import java.io.IOException;

public class SomeCloseable implements Closeable {
    
    SomeCloseable() {
    }
    
    public static SomeCloseable start() throws IOException {
        SomeCloseable result = new SomeCloseable(); // NOSONAR java:S2095
        result.startResources();
        return result;
    }

    public static SomeCloseable startInSomeOtherWay() throws IOException {
        SomeCloseable result = new SomeCloseable(); // NOSONAR java:S2095
        result.startResourcesInSomeOtherWay();
        return result;
    }
    
    
    void startResources() throws IOException {
        // ...
    }

    void startResourcesInSomeOtherWay() throws IOException {
        // ...
    }
    
    @Override
    public void close() throws IOException {
        // ...
    }

}
1 Like