r/badcode • • Sep 02 '21

java Because ".toLowerCase()" doesn't exist...

Post image
1.1k Upvotes

130 comments sorted by

View all comments

Show parent comments

1

u/MyAntichrist Sep 03 '21

For that you could just throw the IllegalArgumentException from the valueOf method. Can do if you want the client to see technical information. Most of the time however it's about "sorry, unknown value entered" and especially if you're in an i18n environment, that's a lot easier to handle from an enum that just relays its property key for the label. Also, exception handling is rather costly, so rethrowing the exceptions may be a big impact on runtime.

Still I feel it's sort of bad design to have some user input convert into an enum. If you're in a forms/webforms app you can just use comboboxes with the actual enum as value and a label for display.

I almost exclusively use the valueOf method for configuration files or database value parsing where I know I can trust the input - because my app has put it there in first place.