Skip to content
Advertisement

Duplicate code across enums .. is there an approach to centralize common code in these enums?

I have the following 3 enum’s in my project, which are all very similar.

Since each enum has at least 2 common fields i.e key and code, is there any way that I can make the common:

  • constructors
  • getters
  • field declarations

shared to all of my enums? Without having to declare inside each one.

I know no extends clause allowed for enum.

But is there an elegant way to achieve reuse of the common parts of these enums?

JavaScript

Advertisement

Answer

Enum – is a special kind of class that is very restricted. And you may think of enum constants as if they are public static final fields (note: explicit modifiers are not allowed with enum constants).

That actually resembles the Singleton pattern.

All enum constants are eagerly initialized when an enum is being loaded into memory. And that is the simplest implementation of the singleton when an instance (in this case instances) is being initialed before any of its static methods of fields can be accessed.

My idea is to introduce an abstract class VehicleType that will contain two string fields key and code, constructor and getters.

And every enum will turn into a concrete class that extends the VehicleType class. Apart from constructors and static final fields in these classes, we’ll need to declare only a single field inside the VanType and provide a getter for it.

The code for that will look like that.

JavaScript
JavaScript
JavaScript
JavaScript
Advertisement