Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try-Catch Instead of Null Check When Using Several Getters

Tags:

java

My problem is the following, I have quite a long Getter, i.e.,

objectA.getObjectB().getObjectC().getObjectD().getObjectE().getName();

Due to "bad" database/entity design (some things were introduced later than others) it happens that getObjectB(), getObjectC() or getObjectD() could return NULL.

Usually we use null-checks all the time, but in this case, I'd have to use

ObjectB b = objectA.getObjectB();
if (b != null) {
    ObjectC c = b.getObjectC();
    if (c != null) {
        ObjectD d = c.getObjectD();
        if (d != null)
           return d.getObjectE().getName();
    }
}
return "";

Instead it would be much easier to simply use a try-catch block

try {
   return objectA.getObjectB().getObjectC().getObjectD().getObjectE().getName();
} catch (NullPointerException e) {
   return "";
}

In this case I don't really care which object returned NULL, it's either display a name or don't. Are there any complications or is it bad design to use try-catch instead of checks?

Thanks for your input.

like image 824
LordAnomander Avatar asked Aug 19 '16 11:08

LordAnomander


People also ask

How do you avoid null?

One way of avoiding returning null is using the Null Object pattern. Basically you return a special case object that implements the expected interface. Instead of returning null you can implement some kind of default behavior for the object. Returning a null object can be considered as returning a neutral value.

Why is checking for null a good practice?

You will often want to say "if this is null, do this", and continue executing. Without the null check you won't get that chance, your whole call stack will be unwound and Unity will go on with the next Update() or whatever method it's going to call. Another is that exception handling is not free.

Should try always be followed by catch?

A try block is the block of code (contains a set of statements) in which exceptions can occur; it's used to enclose the code that might throw an exception. The try block is always followed by a catch block, which handles the exception that occurs in the associated try block.

How do you handle not null in Java?

The nonNull method is a static method of the Objects class in Java that checks whether the input object reference supplied to it is non-null or not. If the passed object is non-null, then the method returns true. If the passed object is null , then the method returns false.


1 Answers

If it is an option to use Java 8, you can use Optional as follows:

Optional.ofNullable(objectA)
    .map(a -> a.getObjectB())
    .map(b -> b.getObjectC())
    .map(c -> c.getObjectD())
    .map(d -> d.getObjectE())
    .map(e -> e.getName())
    .orElse("");
like image 115
Hoopje Avatar answered Oct 07 '22 01:10

Hoopje