I have code like:
obj1 = SomeObject.method1();
if (obj1 != null) {
obj2 = obj1.method2();
if (obj2 != null) {
obj3 = obj2.method3();
if (obj3 != null) {
............
return objN.methodM();
}
}
}
....
I have near 10 steps. It seems very fragile and error prone. Is there a better way to check on null chained methods?
Thanks.
You can use java.util.Optional.map(..)
to chain these checks:
return Optional.ofNullable(SomeObject.method1())
.map(SomeObject2::method2)
.map(SomeObject3::method3)
// ....
.map(SomeObjectM::methodM)
.orElse(null);
You can chain them and surround everything with a try/catch and catch the NPE.
Like this:
try
{
Object result = SomeObject.method1().method2().methodN();
return result;
}
catch(NullPointerException ex)
{
// Do the errorhandling here.
}
Outside that I second @Neil's comment: Try to avoid that kind of chains in the first place.
Votes show that this is very disputed. I want to make sure it is understood, that I do not actually recommend this!
Proceeding like this has many sideeffects and should be generally avoided. I just threw it into discussion for OPs special situation, only as one way to achieve the goal if not otherwise possible!
If anyone feels he needs to do this: Please read the comments for possible pitfalls!
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