How better refactor chain of methods that can retu

2019-02-17 01:23发布

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.

10条回答
我命由我不由天
2楼-- · 2019-02-17 01:46

Try to format this way:

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

if (objN != null) {
   return objN.methodM();
}
return null;

Don't forget to initialize all your objs to null.

查看更多
smile是对你的礼貌
3楼-- · 2019-02-17 01:46
obj1 = SomeObject.method1();
if (obj1 == null) throw new IllegalArgumentException("...");

obj2 = obj1.method2();
if (obj2 == null) throw new IllegalArgumentException("...");

obj3 = obj2.method3();
if (obj3 == null) throw new IllegalArgumentException("...");

if (objN != null) {
   return objN.methodM();
}

Some more discussion here

查看更多
叼着烟拽天下
4楼-- · 2019-02-17 01:49

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.

查看更多
Deceive 欺骗
5楼-- · 2019-02-17 01:51

We can use Java8 Functional Interface approach.

@FunctionalInterface
public interface ObjectValue<V> {
    V get();
}

static <V> V getObjectValue(ObjectValue<V> objectValue)  {
    try {
        return objectValue.get();
    } catch (NullPointerException npe) {
        return null;
    }
}

Object obj = getObjectValue(() -> objectA.getObjectB().getObjectC().getObjectD());
if(Objects.nonNull(obj)) {
//do the operation
}
查看更多
登录 后发表回答