编码这个嵌套条件结构的更好方法是什么?

问题描述 投票:0回答:1

我会用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()

r if-statement conditional nested-if
1个回答
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语言,但上面是我的想法。

© www.soinside.com 2019 - 2024. All rights reserved.