Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
If statement 通用If结构_If Statement_Language Agnostic - Fatal编程技术网

If statement 通用If结构

If statement 通用If结构,if-statement,language-agnostic,If Statement,Language Agnostic,越来越多的我发现自己在写一个If语句的结构,看起来像这样: if(something) { if(somethingElse) { // If both evaluate to true. doSomething(); } else { // If the first if is true but the second is not. doSomethingElse(); } } else { // If the first ev

越来越多的我发现自己在写一个If语句的结构,看起来像这样:

if(something) {
  if(somethingElse) {
     // If both evaluate to true.
     doSomething();
  }
  else {
     // If the first if is true but the second is not.
     doSomethingElse();
  }
}
else {
     // If the first evaluates the false.
     doSomethingDifferent();
}

现在,对我来说,这看起来很可怕。有没有人有更清晰的方式来表达这种逻辑?

问题有三种情况:
某物&somethingelse
某物&!有些东西是
和!一些东西。另一种方法是将其分解为具有三个分支的if-else:

if(something & somethingElse) {
     // If both evaluate to true.
     doSomething();
  }
elif(something) { // explicit test of somethingElse falsity not required
     // If the first if is true but the second is not.
     doSomethingElse();
  }
else {
     // If the first evaluates the false.
     doSomethingDifferent();
}

对于这样一个简单的情况,我通常更喜欢像上面那样将结构展平。对于更复杂的情况,嵌套可能会更简单,或者更好地将测试简化为某种结构(取决于语言的列表或整数)并打开该值

虽然它看起来很糟糕,但很容易调试。我怀疑你的意思是
doSomethingElse()
doSomethingElse2()
(即,3个不同的子例程而不是2个)?我深表歉意@伊奥尼斯,这正是我的意思。这是漫长的一天。谢谢你的关注@Chris可能不是,在逻辑方面,因为有3个子句和3个动作必须显式表示,假设它们是不同的。@Chris:关于您的特定代码,如果您需要所有三个动作都不同,您可能可以反转第一个
if
if(!something)的条件剂量不同;否则,如果(某件事)做了某件事;其他剂量的Thingelse