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.
Try to format this way:
Don't forget to initialize all your
obj
s tonull
.Some more discussion here
More context is necessary to answer this question well.
For example, in some cases I'd advocate breaking out the inner
if
statements into their own methods, following the "each method should do a single thing, completely and correctly." In this case, calling the method and checking for null is that single thing: if it's null, it returns (or throws, depending on your actual needs). If it isn't, it calls the next method.Ultimately I suspect this is a design issue, though, the solution to which is unknowable without insight into the problem being solved.
As it stands, this single chunk of code requires deep knowledge of (what I suspect are) multiple responsibilities, meaning in almost all cases, new classes, new patterns, new interfaces, or some combination would be required to make this both clean, and understandable.
We can use Java8 Functional Interface approach.