0

After long time on Java 7 I am finally converting to Java 8. I am wondering though whats the best construct in this case: lets go directly to example:

class Bar {
    private Foo foo;
    // getters, setters
}

class Foo {
    private String value1;
    private String value2;
    private String value3;
    private String value4;
    // getters, setters
}

What is the best option(al) for checking whether foo is not null and has at least one value filled?

1.

    Optional<Foo> foo = Optional.ofNullable(bar.getFoo());
    if(foo.map(Foo::getValue1).isPresent()
            ||foo.map(Foo::getValue2).isPresent()
            ||foo.map(Foo::getValue3).isPresent()
            ||foo.map(Foo::getValue4).isPresent()){


    }

2.

    Optional<Foo> foo = Optional.ofNullable(bar.getFoo());
    if(foo.filter(foo->foo.getValue1()!=null
    ||foo.getValue2()!=null
    ||foo.getValue3()!=null
    ||foo.getValue4()!=null).isPresent()){

    }
  1. or just use old good nullchecks
    Foo foo1=bar.getFoo();
    if(foo1!=null&&(foo.getValue1()!=null
    ||foo.getValue2()!=null
    ||foo.getValue3()!=null
    ||foo.getValue4()!=null)){

    }

Thank you.

stove
  • 556
  • 6
  • 24
  • 4
    3. Optional is not meant to replace null checks. It's meant to be used as a method return type to signal that the method might return an "absent" value. – JB Nizet Apr 19 '19 at 11:10
  • ok, thanks, because I was reading https://www.baeldung.com/java-optional and the examples suggested it could be used like this. – stove Apr 19 '19 at 11:45
  • 1
    In this case, use #3. Optional can be used in other locations than just return types, such as variables and fields, and it is definitely intended for use on formal parameters. Here is a discussion I wrote on [when to use Optional](https://homes.cs.washington.edu/~mernst/advice/nothing-is-better-than-optional.html). – mernst Apr 20 '19 at 23:33
  • Ok, thank you mernst. – stove Apr 23 '19 at 09:17

0 Answers0