3 ms·
Actually, your way is awfully more verbose, but you didn't notice it because you ellipsized the verbosity. If you actually take the time to translate OP's code
by incepted 11y ago
Actually, your way is awfully more verbose, but you didn't notice it because you ellipsized the verbosity.
If you actually take the time to translate OP's code with your own, you will soon find yourself indented six levels with "if (a != null) { ... if (b != null) { ... if (c != null) {...
You get the idea.
Monads (the type class that Optional belongs to) flatten all this boiler plate with a function called... flatMap! And you don't even need to know about it, all you need to do is chain the calls like OP did:
Optional.ofNullable(paramater)
.filter(...)
.map(a -> ...)
.map(b -> ...)
.orElseGet(() -> ...)
.orElse(defaultValue)
without having to check against null every step along the way.
- norswap 11y agoPoint taken. I'll tentatively argue if all your functions can return null you have other problems to contend with, but what you said makes sense.