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

Build vs Buy a Data Quality Solution: Which is Best for You? Gain insights on a hybrid approach. Download white paper now!

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

Build vs Buy a Data Quality Solution: Which is Best for You? Maintaining high quality data is essential for operational efficiency, meaningful analytics and good long-term customer relationships. But, when dealing with multiple sources of data, data quality becomes complex, so you need to know when you should build a custom data quality tools effort over canned solutions. Download our whitepaper for more insights into a hybrid approach.

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}