5 ms·
> If you used the returned Country to construct an API request including the name of the country, this will now produce strange countries named as “Optional[“No
by bluesign 7y ago
> If you used the returned Country to construct an API request including the name of the country, this will now produce strange countries named as “Optional[“Norway”]”
I am not too familiar with java, but should’t you call get() from optional to get Country from Optional<Country> and toString of Country will behave as expected.
- iainmerrick 7y agoThe point is that if you change the type, existing calls to country.toString() will still compile. (Normally, fixing compile errors is a fairly reliable way to do this kind of refactoring.) That means you can’t guarantee to catch them all, so there’s a risk of modified behavior escaping into production.
- oftenwrong 7y agoAs the sibling comment says, the post's advice is really about making your code refactoring-friendly with regard to type checking. You generally would not want to call '.get()' without an 'isPresent()' check because it will throw a NoSuchElementException if the Optional is empty. This is a foreseeable case, so most would like to handle it somewhat explicitly. Today, it is idiomatic to use '.map' to transform it: Optional<String> foo = optionalCountry.map(Country::getName); You can also throw a domain-specific exception from that point: Optional<String> foo = optionalCountry .map(Country::getName) .orElseThrow(...);
- chopin 7y agoorElseThrow does return a String, not an Optional. You also could use orElse(null) or orElse("null") depending on the use case (eg. using as a part of toString).
- oftenwrong 7y agoI'm useless without a compiler to check my types!