Tag Archive | inheritance

Using interfaces to subdivide enums into smaller semantic units

Recently I stumbled upon a huge enum with a lot of values. While working with this enum I realized, that in some situations you only needed a few enum values while in other situations you needed other values. This clearly indicated that the enum subsumed values from different semantic fields.
But how can you subdivide such a enum into separate units?
A first thought was to establish some kind of inheritance. But Java does not support inheritance for enums. The reason why is shown in the following example:

 enum First {One, Two}   
 enum Second extends First {Three, Four}   

 First a = Second.Four;   // clearly illegal 

But instead of using inheritance one could create separate enums and define a common interface for them:

interface Os {

}
enum WindowsOs implements Os {
    Windows95,
    Windows98,
    ...
}
enum UnixOs implements Os {
    Linux,
    Solaris,
    ...
}

Now you can write methods, that only accept operating systems of type WindowsOs or UnixOs or any Os:

	private boolean isWindowsOs(Os os) {
		return (os instanceof WindowsOs);
	}

	private void rebootAfterInstallation(WindowsOs windowsOs) {
		System.out.println("Rebooting");
	}

Even if you want to refine the UnixOs enum, you could create one more interface (e.g. UnixOs that extends Os) and create enums like LinuxOs and SolarisOs that implement the new interface:

interface UnixOs extends Os {

}
enum LinuxOs implements UnixOs {
    CentOs,
    RedHat,
    Debian,
    ...
}
Advertisements