有什么更好的方法来编码此嵌套条件结构?

时间:2019-02-19 04:51:44

标签: r if-statement conditional nested-if

我将以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,则需要进行修改。

  • condA()is.character()
  • condB()exists()
  • condC()is.data.table()
  • modify1()get()

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

1 个答案:

答案 0 :(得分:0)

长版:

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语言,但这是我的主意。