7 ms·
Using get() is just bad style and so is returning null where you could return Collections.emptyList(). Previous discussion on reddit: https://www.reddit.com/r
by jkscm 11y ago
Using get() is just bad style and so is returning null where you could return Collections.emptyList().
Previous discussion on reddit:
https://www.reddit.com/r/programming/comments/3pl7o0/java_8s_new_optional_type_is_worthless/ https://www.reddit.com/r/programming/comments/3pl7o0/java_8s...
tl;dr: use map, orElseGet, orElse
- vbezhenar 11y agoWhy it's bad? If I'm sure that this optional contains value, I don't see why it's bad. May be I checked this value presence few lines above.
- serpix 11y agoIf you are certain optional has a value, don't use optional. Checking presence of value of an optional is an anti-pattern, the same as doing != null checks. You should treat Optional the same as a List type with size 1. You never check if a list is size 1 before doing map or filter.
- vbezhenar 11y agoI'm not always own code. Simple example: getCharsetOpt("UTF-8") There is no way this code will return None in this particular case. So any additional checks are unnecessary and make code less readable.
- louthy 11y agoI don't know who said it, and this is probably a paraphrase: "If it can't happen, it will". If a function says the result is optional, then it's optional. It's not not optional because you decided it can't ever fail.
- nrinaudo 11y agoI feel get is acceptable style if you actually want to fail when there is no data to be had. If you don't have a default value to provide, nor an alternate code path other than "sod this, I'm bailing", get is ok. Not quite as good as using a more specific exception through orElseGet, but not bad, exactly. Also, if you have just called isPresent (and assume your data to be immutable), then get is ok - the alternative being to manually throw something like new IllegalStateException("the impossible has happened!"), which is not that much more useful, and is a pain to have to write all the time when you know it will not get called.
- krisdol 11y ago>Using get() is just bad style and so is returning null where you could return Collections.emptyList(). I agree that you should never return null, but if get() is bad style I think you should send out that memo because I haven't yet seen codebases that agreed.