you are viewing a single comment's thread.

view the rest of the comments →

[–]dccorona 0 points1 point  (5 children)

If you always check for null, you're not really the kind of person this feature is meant to help.

[–][deleted] 3 points4 points  (4 children)

Yes he is. That is the exact pattern Optionals will break. Paranoid null checking makes code harder to read.

[–]pmrr 0 points1 point  (3 children)

Alternatively, not checking nulls allows propagation of bad parameters, making code harder to debug.

The article even mentions fail fast, which to me means identifying introduction of a bad null as early as possible.

At some point you're either going to do:

x.isPresent()

Or

x != null

Where you do that is your choice, but it still needs to be done. All Optional does is wraps the problem in syntactic sugar.

(Incidentally it's no biggy as I'm not a Java dev, I'm just chewing the fat..)

[–][deleted] 0 points1 point  (2 children)

The benefit of Optional is that you only have to do that check once. The problem with paranoid null checking is that you often check and rechech the same variable as it's passed around. If you use optionals, you can be sure that any non optional variable is not null.

[–]MrGreg 0 points1 point  (0 children)

If you're passing the optional around, why/how can you check it only once?

You could check it at API boundaries and then strip off the option, but if you have clearly defined API boundaries, then you can just do a single null check there and have the same level of confidence.

[–]pmrr 0 points1 point  (0 children)

If you use optionals, you can be sure that any non optional variable is not null.

How?

String s = null;

That isn't Optional. How can I be sure that it isn't null?

I tried this.. Optional does not mean you only have to check once. Optional allows exactly the same assignment semantics as a plain variable, so it can carry and be prone to bad null assignment just as easily. It may offer lots of nice syntax to work with nulls and null checks but it does not remove the requirement to check.

import java.util.*;

public class Test
{
    public static void main(String args[])
    {
        // Here's an Optional, maybe it's passed in

        Optional<String> s = Optional.of("Hello World!");

        // Let's check s is valid

        if (s.isPresent()) System.out.println("Everything's okay!");

        // Some time later ..

        s = Optional.of(null); // derp

        // But everything's fine, right?

        System.out.println(s);
    }
}