如何更好的重构方法链可以在java中返回null? [英] How better refactor chain of methods that can return null in java?

查看:141
本文介绍了如何更好的重构方法链可以在java中返回null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码如下:

obj1 = SomeObject.method1();
if (obj1 != null) {
  obj2 = obj1.method2();
  if (obj2 != null) {
     obj3 = obj2.method3();
     if (obj3 != null) {
              ............


     return objN.methodM();

   }
  }
 }
....

我差不多10步了。它似乎非常脆弱且容易出错。有没有更好的方法来检查空链方法?

I have near 10 steps. It seems very fragile and error prone. Is there a better way to check on null chained methods?

谢谢。

推荐答案

这是<$ c $的常见问题c> null java中的引用。

It's common problem for null references in java.

我更喜欢用&& 链接:

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

这篇关于如何更好的重构方法链可以在java中返回null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆