Hacker News new | ask | show | jobs
by noamsml 3710 days ago
I disagree. I'd rather getWhenPresent than orElse if the code has nothing to do with a missing value. If someone needs the value and uses orElse without isPresent, their code will break in new and unexpected ways rather than in the obvious one.

(An even better solution is SWIFT's approach to nullable types, but that boat has sailed; intellij etc could however implement a static checker for bare Optional-getting)

1 comments

How does orElse() cause new problems and/or break code? It is the same as get but forces you to think about the not available option...?

I think the options orElse/orElseGet and orElseThrow are enough to replace every get() method, and they'll force you to think about the missing scenario.

If you want to do something in case it is present, use ifPresent(lambda).

In case you want to return something, use orElse/orElseGet or orElseThrow, or just return the Optional itself.

> I think the options orElse/orElseGet and orElseThrow are enough to replace every get() method, and they'll force you to think about the missing scenario.

orElseThrow doesn't force you to think about the missing scenario, only to think about which exception you want to throw, which in many case you don't care for.

If orElseThrow had an override throwing NoSuchElementException by default it would be a perfect replacement, alas it does not.

Of course it does, you actively choose to throw something! That is, in some cases, perfectly acceptable. All three methods tell you there is something else in case you don't have a value in the optional. get() doesn't.