1

This is more a general question than a specific one.

I'm doing a project where we came to the conclusion that it might be smartest to use enums for something we call "operation". We have one of these so-called operations which needs a secondary attribute "Roles" but I'm not sure if I can have one value from my enums to have a secondary attribute while the others don't have one.

Hope my question make sense even though I don't have any code xD

user207421
  • 305,947
  • 44
  • 307
  • 483
Oliver
  • 25
  • 3

1 Answers1

1

Yes, it is totally possible, however it depends on how you want to handle the absence of field from one enum to the other.

Here are two propositions

Using an exception

enum TheEnum {
    WITHOUT_ROLE, WITH_ROLE(() -> "boss");

    private Supplier<String> roleSupplier;

    TheEnum() {
        this(() -> {throw new NoRoleException();}); 
    }

    TheEnum(Supplier<String> roleSupplier) {
        this.roleSupplier = roleSupplier;
    }

    String getRole() {
        return roleSupplier.get();
    }
}

Using null

enum TheEnum {
    WITHOUT_ROLE, WITH_ROLE(() -> "boss");

    private String role;

    TheEnum() {
        this(null); 
    }

    TheEnum(String role) {
        this.role = role;
    }

    // The use of Optional is not mandatory, even more if you know how to handle nulls yourself and are not exposing this enum
    Optional<String> getRole() {
        return Optional.ofNullable(role);
    }
}
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89