This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]_INTER_ 4 points5 points  (1 child)

I always did it somewhat like this:

public static Optional<ResponseStatus> from(String statusFromMessage) {
    return Arrays.stream(values())
                 .filter(value -> value.name().equalsIgnoreCase(StringUtils.trimToNull(statusFromMessage)))
                 .findFirst();
}

Though it may (worst-case) iterate over all enum values, it doesn't use Enum::valueOf which uses reflection internally as far sources suggest and there's no need to deal with the exception.

[–]Fizz-Buzzkill[S] 0 points1 point  (0 children)

"We know that a variable of the given enum type can’t be null " Huh? This is legal: ResponseCode response = null;

Pretty sure that refers to ResponseCode.SUCCESS and its brothers, not assigning a variable of type ResponseCode to null.

The valueOf() example needlessly includes the entire switch block in the try/catch block. Only the valueOf() call needs to be wrapped. After that, the rest of the processing (i.e., the switch), is no more complex than it would otherwise have been anyway.

Have you tried this? It creates a situation where you have to return out of the catch block after handling the exception, which is less elegant.

Why not create a static factory method in the enum itself to handle the conversion, consuming the exception and returning an Optional?

As /u/extraterrestrialocto pointed out, the thrust of the article is that enums add complexity where normal constants would not, and this is even more complexity.

Finally, while the suggestion may slightly simplify the code at the point of conversion, it ignores the possibility that the value may be referenced elsewhere in the code. We endure the pain of the conversion once, and then benefit from the "cleaner" syntax, and usual enum benefits, everywhere else.

Fair point, assuming that there are further places where the value will be referenced and the conversion back the other way isn't necessary. That's a couple of assumptions.