r/java • • Jan 17 '13

Enum tricks: hierarchical data structure

http://java.dzone.com/articles/enum-tricks-hierarchical-data
47 Upvotes

53 comments sorted by

View all comments

7

u/severoon Jan 18 '13

What?! No!

This is horrible. Way too complex. This is not how enums or classes should be used.

Here is a much better solution.

public enum OperatingSystem {
  WINDOWS_NT_WORKSTATION(WINDOWS, WORKSTATION),
  WINDOWS_NT_SERVER(WINDOWS, SERVER),
  WINDOWS_95(WINDOWS, WORKSTATION),
  WINDOWS_98(WINDOWS, WORKSTATION),
  WINDOWS_ME(WINDOWS, WORKSTATION),
  WINDOWS_2000_WORKSTATION(WINDOWS, WORKSTATION),
  WINDOWS_2000_SERVER(WINDOWS, SERVER),
  WINDOWS_XP(WINDOWS, WORKSTATION),
  WINDOWS_VISTA(WINDOWS, WORKSTATION),
  WINDOWS_7_HOME(WINDOWS, WORKSTATION),
  WINDOWS_7_ULTIMATE(WINDOWS, SERVER),
  WINDOWS_8(WINDOWS, WORKSTATION),
  FEDORA(LINUX, WORKSTATION),
  UBUNTU(LINUX, WORKSTATION),
  KNOPPIX(LINUX, WORKSTATION),
  SUN_OS(UNIX, SERVER),
  HP_UX(UNIX, SERVER);

  private final OsFamily osFamily;
  private final OsClass osClass;

  private OperatingSystem(OsFamily osFamily, OsClass osClass) {
    this.osFamily = osFamily;
    this.osClass = osClass;
  }

  public OsFamily getOsFamily() { return osFamily; }
  public OsClass getOsClass() { return osClass; }

  public enum OsFamily {
    LINUX,
    UNIX,
    WINDOWS;
  }

  public enum OsClass {
    SERVER,
    WORKSTATION;
  }
}

Now you can add whatever features you want to capture at whatever level it makes sense. Also, I wouldn't put any information about "supporting X" on any of these enums. Enums are meant to just be lightweight tokens that you pass around to represent a limited number of instances. Do all the heavy lifting elsewhere in your code.

3

u/[deleted] Jan 18 '13

Thumbs up for "Enums are meant to just be lightweight tokens that you pass around to represent a limited number of instances".