1

I am trying with Optionals and I am pretty sure my solution is not good. I put a little sample below.

class Person {
    String name;    // can be null
    Integer age;    // can be null
}

class DB {
    // returns an Optional
    public static Optional<Person> getPerson() {
        //irrelevant code here
    }
}



public static void main() {
    Person p = DB.getPerson().orElse(null);

    // did I get a Person?
    if (p != null) {
        // both information of a Person available?
        if (p.name != null && p.age != null) {
            dosomthing (p.name, p.age);
        }
    }
}

Any idea how to improve this? I see HERE no benefit in using Optionals. But I am not in charge of getPerson.

4
  • If you just call getPerson() without the orElse, you'll receive an Optional<Person>. Then you can check things like p.isPresent() instead of p != null. Although the example feels a little contrived Commented Dec 17, 2020 at 10:38
  • If a Person's name and age cannot be null, can't you just make them non-nullable? If that's not possible, you could have dosomthing do the checks before running any operation. Commented Dec 17, 2020 at 10:38
  • Are you sure that you didn't mean to make getName() and getAge() return Optional, as they are the things you indicate can be null? Commented Dec 17, 2020 at 10:39
  • If you are not in charge of getPerson, you can't really improve this... Ideally no person should have no name or age. getPerson should return an empty optional in such cases. Commented Dec 17, 2020 at 10:40

1 Answer 1

1

So what about using Optional like this;

DB.getPerson()
        .filter(p -> p.name != null && p.age != null)
        .ifPresent(p -> dosomthing(p.name, p.age));

I assume you are using Optional::ofNullable in getPerson()

Sign up to request clarification or add additional context in comments.

1 Comment

No need to do .filter(Objects::nonNull). An Optional cannot contain null. It would just be empty.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.