Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NULL safe object checking in JAVA 8

So i want to do a null safe check on a value contained within a value.

So I have 3 objects contained within each other:

Person has a clothes object which has a country object which has a capital

So a person may not have clothes so a check like this throws a null pointer:

if (person.getClothes.getCountry.getCapital)

How would I make a statement like this just return false if any of the objects on the path are null?

I also don't want to do it this way. (A one-liner in Java-8 if possible.

if (person !=null) {
    if (person.getClothes != null) {
        if (person.getClothes.getCountry !=null) {
            etc....
        }
    }
}
like image 622
Blawless Avatar asked Sep 07 '18 10:09

Blawless


People also ask

How do you handle a null object in Java 8?

Using … != null still is the way to do it in Java 8 and even Java 11.

How do you do null check for object in Java?

In order to check whether a Java object is Null or not, we can either use the isNull() method of the Objects class or comparison operator.

What is null safe in Java?

Void safety (also known as null safety) is a guarantee within an object-oriented programming language that no object references will have null or void values. In object-oriented languages, access to objects is achieved through references (or, equivalently, pointers).

Which method is used to check null on an Optional variable Java 8?

Let's learn how to use Java 8's Optionals to make your null checks simple and less error-prone! Join the DZone community and get the full member experience. The method orElse() is invoked with the condition "If X is null, populate X. Return X.", so that the default value can be set if the optional value is not present.


2 Answers

You can chain all of those calls via Optional::map. I sort of find this easier to read than if/else, but it might be just me

Optional.ofNullable(person.getClothes())
        .map(Clothes::getCountry)
        .map(Country::getCapital)
        .ifPresent(...)
like image 120
Eugene Avatar answered Sep 20 '22 12:09

Eugene


These "cascade" null-checks are really paranoid and defensive programming. I'd start with a question, isn't better to make it fail fast or validate the input right before it's store into such a data structure?

Now to the question. As you have used nested the null-check, you can do the similar with Optional<T> and a method Optional::map which allows you to get a better control:

Optional.ofNullable(person.getClothes())
        .map(clothes -> clothes.getCountry())
        .map(country -> country.getCapital())
        .orElse(..)                               // or throw an exception.. or use ifPresent(...)
like image 27
Nikolas Charalambidis Avatar answered Sep 20 '22 12:09

Nikolas Charalambidis