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

Just released, a free O’Reilly book on Reactive Microsystems: The Evolution of Microservices at Scale. Brought to you in partnership with Lightbend.

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

Strategies and techniques for building scalable and resilient microservices to refactor a monolithic application step-by-step, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}