3 ms·
> Having the get() method makes the entire purpose of Optional useless. It doesn't quite, though it is way too short and convenient. > If you need to extract
by masklinn 11y ago
> Having the get() method makes the entire purpose of Optional useless.
It doesn't quite, though it is way too short and convenient.
> If you need to extract the value, the orElse method should be suitable on all cases.
orElse is incorrect if you have specific expectations. get is an assertion, and used in that manner it's perfectly sensible and orElse is not. Plus orElse can send the wrong signal.
> Including it in the first place was as much of a mistake as the null pointer.
The only language I know which has optionals and doesn't have something equivalent to .get() is Elm, and even there you can trivially pattern-match and call Debug.crash in the Nothing case.
- weego 11y agoYou should never have concrete expectations or make assertions on an unknown, that's the entire point of any implementation of Option. Option.get leads to false confidence. I've had many arguments over use .get (in Scala) where another developers argument is "we check that it's defined higher up in the code". At that point a harmless looking refactor by someone else can introduce NPEs.
- masklinn 11y ago> You should never have concrete expectations or make assertions on an unknown As long as Optional#isPresent exists, you can have "concrete expectations" of an optional's content (or lack thereof). > At that point a harmless looking refactor by someone else can introduce NPEs. The fundamental problem is not .get, it's that you're qualifying code changes involving partial function as "harmless-looking" and "refactoring"
- pcwalton 11y agoOption.get is important. It lets you work around the type system in cases where the type system wasn't expressive enough. Given that all type systems are imprecise, this functionality is essential. I'm all for strong type systems, but I also acknowledge their limitations.
- gozur88 11y agoIf someone has managed to bork the code with a harmless looking refactor, an NPE is what you want. The code is no longer working as designed and needs to be fixed.
- matt_kantor 11y agoRemember that in this scenario the alternative to an NPE is that the program doesn't even compile (because it won't type check).