Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Complex initialization of a static field

DZone's Guide to

Complex initialization of a static field

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

With all these IoC libraries around, it's still often necessary to grab some factory to be used later. It's great if you can get it with a plain method call without checked expressions:

private static final SAXParserFactory PARSER_FACTORY = SAXParserFactory.newInstance();

But still there are cases when someone has decided to throw a checked exception from similar calls. This won't compile:

private static final DatatypeFactory DATATYPE_FACTORY = DatatypeFactory.newInstance();

A common solution would be to add a static initializer. Even my IDE proposes that:

    private static final DatatypeFactory DATATYPE_FACTORY;
    static {
        try {
            DATATYPE_FACTORY = DatatypeFactory.newInstance();
        } catch (DatatypeConfigurationException e) {
            throw new IllegalStateException(e);
        }
    }

But a problem can arise when you refactor. Constants can be easily moved to another (e.g. parent or utility) class. And a static initializer, if forgotten, won't be executed until after its class is loaded. 

So my recommendation is to use a static function to do same work:

    private static final DatatypeFactory DATATYPE_FACTORY = newDatatypeFactory();
    private static DatatypeFactory newDatatypeFactory() {
        try {
            return DatatypeFactory.newInstance();
        } catch (DatatypeConfigurationException e) {
            throw new IllegalStateException(e);
        }
    }

It's easy. The number of lines has not increased, and you instantly get benefits:

  • You can easily navigate to your initialization code
  • Any refactoring will highlight the initialization method to be moved along with the field
  • Even if you forget to move it for some reason, it will still be called

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}