2
\$\begingroup\$

I have situation where user has got options to select, and after selected any option will appear next options. For example : 1 - Add car 2 - Add motorcycle. 3 - Print cars 4 - Print motorcycles

And after selected for example "1" console will show options like : 1 - Add passenger car, 2 - Add light commercial car. At this moment i have two enum classes in two separated files that has got almost the same code inside, and same methods createFromInt() which returns Options according to int provided by the user, and toString().Exmple one of two enums(The second one is almost the same except the fields) :

enum Option {
ADD_CAR(0,"Add car"),
ADD_MOTORCYCLE(1,"Add motorcycle"),
PRINT_CARS(2,"Print cars"),
PRINT_MOTORCYCLES(3, "Print motorcyces"),

private int value;
private String description;

Option(int value, String description) {
    this.value = value;
    this.description = description;
}

@Override
public String toString() {
    return value + "-" + description;
}

public static Option createFromInt(int option) throws NoSuchOptionException {
    try {
        return Option.values()[option];
    }catch (ArrayIndexOutOfBoundsException ex) {
        throw new NoSuchOptionException("Brak opcji o ID: " + option);
    }
}

}

I was just wondering is it corectly locate these enums in two files or exists any more elegant way for example one file with two enums , or nested enums (if something like that at all exists).

\$\endgroup\$
2
\$\begingroup\$

At first, I think you don't need the value field. Indeed, as shown in createFromInt, you refer to enum values with their position (Option.values()[option]).

I suggest the following refactoring.

enum Option {
  ADD_CAR("Add car"),
  ADD_MOTORCYCLE("Add motorcycle"),
  PRINT_CARS("Print cars"),
  PRINT_MOTORCYCLES("Print motorcycles");

  private String description;

  Option(String description) {
    this.description = description;
  }

  @Override
  public String toString() {
    return this.ordinal() + "-" + description;
  }

  public static Option getFromIndex(int optionIndex) throws NoSuchOptionException {
    if (optionIndex >= 0 && optionIndex < values().length) {
      return Option.values()[optionIndex];
    }
    throw new NoSuchOptionException("Brak opcji o ID: " + optionIndex);
  }
}

I prefer getFromIndex because the argument is an index or a value and you don't create new instances of the enum.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ You should protect against negative optionIndex values in getFromIndex(), not just too large values. \$\endgroup\$ – AJNeufeld Sep 2 '19 at 3:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.