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.
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.
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.
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.
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.
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("");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With