首页 > 解决方案 > 编写这种嵌套条件结构的更好方法是什么?

问题描述

我会以 R 为例:

# x is an object
# condA(x), condB(x) and condC(x) evaluate x and return TRUE or FALSE
# The conditions must be evaluated in the following orders.
#   For e.g., when validating for an random object being a number larger than 5,
#   you always need to evaluate whether it is numeric first,
#   only after which can you evaluate whether it is larger than 5.
#   Trying to evaluate both at once will cause an error if it is non-numeric.
# process1() and process2() are two different procedures
# modify1() is a modifier for x
if (condA(x)) {
  if (condB(x)) {
    x %<>% modify1
    if (condC(x)) {
      process1()
    } else {
      process2()
    }
  } else {
    process2()
  }
} else {
  if (cond(C)) {
    process1()
  } else {
    process2()
  }
}

这样我需要多次指定每个过程,并重复评估 condC(x) 的部分,我觉得这样做很笨拙。有什么建议可以用更优雅的方式来编码这个结构,这样我只需要提到一次 process1() 和 process2() ,而不会破坏上述代码中所述的评估顺序?


更多信息: 我想这是一个普遍的问题,但也许一个例子可以促进讨论......假设如果condB(x)评估需要修改TRUE

因此,如果x是一个字符,它应该表示一个对象名称,然后验证其存在,然后转换为对象的指针。如果x不是字符,它应该指向目标对象。然后验证目标对象(由 指向x)以查看它是否为data.table。如果是,process1(),否则process2()

标签: rif-statementconditionalnested-if

解决方案


长版:

boolean A = condA(x);
boolean B = false;
boolean C = false;

if (A) {
    B = condB(x);
}

if (A && B || !A) {
    C = condC(x);
}

if (C) {
    process1();
} else {
    process2();
}

精简版:

boolean A = condA(x);
boolean B = A && condB(x);
boolean C = (A && B || !A) && condC(x);

if (C) {
    process1();
} else {
    process2();
}

PS:我不确定R语言,但以上是我的想法。


推荐阅读