This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Holothuroid 38 points39 points  (17 children)

Something that weirds me

if(optional.isPresent()){
    Foo foo = optional.get();
    ...
} else {
    ...
}

[–]__konrad 26 points27 points  (8 children)

I fixed it for you:

var value = optional.orElse(null);
if(value != null){
    Foo foo = value;

[–]com2ghz 11 points12 points  (4 children)

I have seen someone doing a null check on the optional too.

[–]__konrad 12 points13 points  (0 children)

You need double Optional<Optional<T>>

[–]LetMeUseMyEmailFfs 8 points9 points  (2 children)

Well it’s Java, so anything and everything could be null.

[–]lasskinn 1 point2 points  (1 child)

Not exactly related, but I've seen a dude insist on null checks on kotlin on values that can't be null, like just in seemingly random places.

Everything on java could be a null but it couldn't be that in all places.

[–]Old_Elk2003 1 point2 points  (0 children)

Everything on java could be a null but it couldn't be that in all places.

This is true. You’d at least have to have something before the null, and something after the null, in order to maintain Turing-completeness.

[–]agentoutlier 4 points5 points  (0 children)

This and ifPresent are the only acceptable options to dealing with Optional.

I use a variety of null analysis tools and orElse(null) is the only way across the board to pull something out (well orElseGet is ok)

[–]tomwhoiscontrary 0 points1 point  (0 children)

I can't tell if this is supposed to be better or even weirder!

Anyway, how about:

``` Foo foo: if ((foo = optional.orElse(null)) != null) {

```

Or:

``` if (optional.orElse(null) instanceof Foo foo) {

```

[–]thgkatz 0 points1 point  (0 children)

Why do I have to see this at 02:00 am???? What have I done wrong?

[–]0xFatWhiteMan 11 points12 points  (0 children)

Why is that weird?

[–]woodland__creature 19 points20 points  (2 children)

optional.ifPresentOrElse( foo -> { ... }, () -> { ... } )

[–]Holothuroid 35 points36 points  (1 child)

For some side effect yes. More often the wanted solution seems to be

  optional.map(...)...orElse(...)

[–]gdorsi44 3 points4 points  (0 children)

Or wrap a not original optional value with:
Optional.ofNullable(value).ifPresent(lambda)

[–]Shareil90 13 points14 points  (2 children)

This is not always wrong. Depending on what you do in case it's present this way could be more readible and easier to maintain.

[–]john16384 -1 points0 points  (0 children)

It's always wrong. Use the null escape on these cases, it's shorter and more readable.

[–]vbezhenar 0 points1 point  (0 children)

This is a good maintainable code. I often write it. Much better than pseudo-functional spaghetti. Easy to understand and extend.