Search code examples
javamethodsnullrefactoringchain

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?

Thanks.


Solution

  • It's common problem for null references in java.

    I prefer chaining with &&:

    if (obj1 != null && obj1.method1() != null && obj1.method1().method2() != null)