1

I have an Enum class that requires a function object (in this case, one of Guava's StringConverters) to initialize one of the fields. It could look like this:

private MyEnum(String input) {
  this.myField = someFunctionObject.convert(input);
}

However, once all the members of the enum are finished loading, I have no use for this object. What's the best practice for handling this? It seems my options are:

  1. Have a private static object somewhere that persists after the enum is finished initializing, creating a pseudo-memory leak. (I could also null it out when I'm done, but then I still have a useless static reference which still is ugly.)
  2. Create and re-create the object each time the enum constructor is called.
  3. Make the field non-final and use a static initializer block that only needs to create the function object once, then loops over the enums and initializes the fields outside of the constructor.

It's not like this is a big deal, but this process has come up a few times, and I don't like any of these solutions. I don't think this is an issue of premature micro-optimization, either, it's an issue of the most elegant/ readable/ sensible way to perform this.

codebreaker
  • 763
  • 1
  • 7
  • 24

1 Answers1

2

I think a variation on option 2 would be fine, since the constructors are only called X times for an enum of X values.

Static initializers are very ugly and instantly raise the warning flag whenever I see them. A static object that is later nulled is similarly not so elegant either.

If you can live with a factory call, all of the "static awfulness" can be confined to a factory class.

private MyEnum(String input) {
    this.myField = SomeFunctionFactory.getInstance().convert(input);
}

Please also see here, there is a way to do this via dependency injection frameworks:

Inject bean into enum

Community
  • 1
  • 1
vikingsteve
  • 38,481
  • 23
  • 112
  • 156