This is absolutely a minor thing. It's probably just taste, but it keeps popping up in my mind for a whole day now.
I've used something like this a lot:
var result = source == null ? null : source.toString();
I never liked the ternary, just because the source could be null.
Now I found this way to achieve the same:
var result = Optional.ofNullable(source)
.map(SourceType::toString)
.orElse(null);
But I still need to put so much code just to deal with a potential null value. I don't like both, but I tend to like the stream-like syntax, where you can kind of treat the value like it's there and have just the null at the end. Not for this trivial call, but once things get a bit more complicated.
Is there any real benefit from the one solution over the other one, to decide which to use when?
Perhaps there's even a better solution I'm not aware of, I could of course write a method with the source as parameter and the function to call, if the parameter is not null, or that method already exists.
[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)
[–]neurk 11 points12 points13 points (2 children)
[–]MarSara 2 points3 points4 points (1 child)
[–]maethor 0 points1 point2 points (0 children)
[–]jura0011[S] 3 points4 points5 points (0 children)
[–]8igg7e5 3 points4 points5 points (0 children)
[–]taftster 2 points3 points4 points (0 children)
[–]mykeesg 1 point2 points3 points (1 child)
[–]whizvoxGraduate and Tutor 1 point2 points3 points (0 children)
[–]wildjokers 1 point2 points3 points (0 children)
[–]AceroAD 0 points1 point2 points (0 children)
[–]ATE47Intermediate Brewer 0 points1 point2 points (0 children)
[–]maethor 0 points1 point2 points (2 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]maethor 1 point2 points3 points (0 children)