0

I have the below method to map various enums in my project to their name but sonar is complaining Code smell·Provide the parametrized type for this generic.

public static String mapToName(Enum customEnum) {
        return Optional.ofNullable(customEnum).map(Enum::name).orElse("");
    }

Its impossible to create separate mapToName method for tens of enums in my project, how do I make the above method sonar compliant?

Naman
  • 27,789
  • 26
  • 218
  • 353
OTUser
  • 3,788
  • 19
  • 69
  • 127

2 Answers2

3

First of all, please do not use Optional as replacement for if-else statements. They were not intended for that purpose. Optional was intended to convey the possibility of null-values in public interfaces in code, instead of just documentation, and only that. Even using optional in a private method is against it's intention (you're supposed to know what your own code does).

Please read this answer from one of the architects behind the Optional class: Should Java 8 getters return optional type?

As an excercise, you should go through the source code for Optional and count how many throwaway objects you create for each name mapping operation.

As for your problem, this is the correct way to solve the immediate Sonar complaint:

public static String mapToName(Enum<?> customEnum) {
    return customEnum == null ? "" : customEnum.name();
}

The question mark is a wildcard which denotes an unknown type.

Torben
  • 3,805
  • 26
  • 31
1
public static <T extends Enum<T>> String mapToName(Enum<T> customEnum) {
    return Optional.ofNullable(customEnum).map(Enum::name).orElse("");
}

If you are pondering about the strange T extends Enum<T>: Why in java enum is declared as Enum<E extends Enum<E>>

Erez Ben Harush
  • 833
  • 9
  • 26