My Java code has improve dramatically since I started (ab)using Optionals. String foo = Optional.ofNullable(paramater) .filter(...) .map(a -> ...) .map(b -> ...) .orElseGet(() -> ...) .orElse(defaultValue) Between this kind of thing, and similar playing with Streams, some of the ugliest code I work with is suddenly quite clear, coherent, understandable.
Two things. First, why is it better than: String foo; if (parameter != null) { foo = ... ; } else { foo = defaultValue; } or even this, if you express all your transformations as a single expression: String foo = parameter != null ? ... : defaultValue I don't get it. Your way of doing seem awfully more verbose. Please note that I'm not against Optional in general (although they are overplayed in my opinion). Second t…
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.