Sean Connolly
Sean Connolly

Reputation: 5801

FindBugs: static instance initialization within class

FindBugs is reporting a bad practice in my code, findbugs:SI_INSTANCE_BEFORE_FINALS_ASSIGNED.

The class's static initializer creates an instance of the class before all of the static final fields are assigned.

My code looks something like..

public class Foo {

    public static final Foo DEFAULT = new Foo(Bar.A, "baz");

    public enum Bar {
        A, B
    }

    private final Bar bar;
    private final String baz;

    public Foo(Bar bar, String baz) {
        this.bar = bar;
        this.baz = baz;
    }

}

I understand it's flagging the use of new Foo as a static variable within Foo as a bad practice, but don't really see the problem.

Can anyone explain why this is bad practice, what unintended behavior might happen with use of this bad practice, and maybe propose a better practice as an alternative?

Upvotes: 2

Views: 1023

Answers (1)

Andy Turner
Andy Turner

Reputation: 140484

You could refer to DEFAULT in the constructor, or a method called directly or indirectly by the constructor. If you did, its value would be null, which may have undesirable consequences for the initialisation of the instance you ultimately assign to DEFAULT.

You don't refer to it in this way, so it isn't really a problem here - currently. However, the class could be changed in the future to refer to it accidentally.

In your example code, it looks like a very cheap class to instantiate. You could simply provide a static factory method, getDefault(), to create a new instance whenever required. If it is not quite as cheap in reality, you could employ some form of lazy initialization.

Upvotes: 1

Related Questions