user710818 user710818 - 2 years ago 67
Java Question

How better refactor chain of methods that can return null in java?

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?


Answer Source

It's common problem for null references in java.

I prefer chaining with &&:

if (obj1 != null && obj1.method1() != null && obj1.method1().method2() != null)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download