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.
If you want are so trusting of your source objects that you plan to chain six of them together, then just continue to trust them and catch exceptions when they are thrown - hopefully rarely.
However if you decide not to trust your source objects, then you have two choices: add compulsive "!= null" checks everywhere and don't chain their methods...
OR go back and change your source object classes and add better null handling at the root. You can do it by hand (with null checks inside setters, for example), or alternatively you can use the Optional class in Java 8 (or Optional in Google's Guava if you're not on Java 8), which offers an opinionated null-handling design pattern to help you react to unwanted nulls the moment they are introduced, rather than wait for some poor consumer to encounter them later on.
I thinh this kind of question was already answered here. Especially see the second aswer about Null Object Pattern .
For getter method who has no parameter , try this:
for most of the cases, it works well. Basically, it is trying to use java reflection to do the null check layer by layer, till it reach the last getter method , since we do a lot cacheing for the reflection, the code works well in production. Please check the code below.
It's common problem for
null
references in java.I prefer chaining with
&&
:You can chain them and surround everything with a try/catch and catch the NPE.
Like this:
Outside that I second @Neil's comment: Try to avoid that kind of chains in the first place.
EDIT:
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!
Write like
etc. As a C developer this is a very common paradigm and is extremely common. If it's not possible to convert your code to this flat flow then your code needs to be refactored in the first place, regardless of what language it exists in.
Replace
return
with whatever you are actually doing in the case where these fail, whether that bereturn null
,throw
an exception, etc. - you've omitted that part of your code but it should be the same logic.