if-statement – 如果没有上述内容,那么做一个优雅的方式是什么?

我相信你一直在那里.你想说“如果flib这样做,如果flob这样做,如果松弛做饮食等”,其中任何数量都可以是真的,那么最后你想要一个“如果你没有做任何一个”.

例如(下面的例子是在Swift中,因为我一直在玩它,但我认为大多数语言的情况都是一样的):

let thing = 101
var isInteresting = false
if (thing % 3 == 0) {
    println("\"\(thing)\" is a multiple of three.")
    isInteresting = true
}
if (thing > 100) {
    println("\"\(thing)\" is greater than one hundred.")
    isInteresting = true
}
if (thing > 1000) {
    println("\"\(thing)\" is greater than one thousand.")
    isInteresting = true
}
if !isInteresting {
    println("\"\(thing)\" is boring.")
}

我发现跟踪一个布尔值告诉我是否做了什么或者没有笨拙.

我想出的唯一另一种方式是:

let thing = 101
let isAMultipleOfThree = (thing % 3 == 0)
let isGreaterThan100 = (thing > 100)
let isGreaterThan1000 = (thing > 1000)

if isAMultipleOfThree {
    println("\"\(thing)\" is a multiple of three.")
}
if isGreaterThan100 {
    println("\"\(thing)\" is greater than one hundred.")
}
if isGreaterThan1000 {
    println("\"\(thing)\" is greater than one thousand.")
}
if !(isAMultipleOfThree  || isGreaterThan100 || isGreaterThan1000 ) {
    println("\"\(thing)\" is boring.")
}

但如果有什么更糟糕的话(如果你添加一个新的条款,你需要记住在三个地方添加它.

所以我的问题是,有一种简洁,简洁的方法吗?

我梦想着一个虚构的开关式声明:

switchif {   //Would have fallthrough where every case condition is checked
case thing % 3 == 0:
    println("\"\(thing)\" is a multiple of three.")
case thing >100 :
    println("\"\(thing)\" is greater than one hundred.")
case thing > 1000:
    println("\"\(thing)\" is greater than one thousand.")
none:   //Unlike 'default' this would only occur if none of the above did
    println("\"\(thing)\" is boring.")
}

最佳答案 这是一个没有完美答案的好问题.但是,除了你建议的那些之外,还有另外一个想法:在一个过程中封装测试机器,以使调用代码至少更加简化.

具体来说,对于您的示例,调用代码可以是:

if (! doInterestingStuff(101)) {
  println("\"\(thing)\" is boring.");
}

如果测试被封装到一个过程中:

  public boolean doInterestingStuff(int thing) {
    var isInteresting = false

    if (thing % 3 == 0) {
      println("\"\(thing)\" is a multiple of three.")
      isInteresting = true
    }
    if (thing > 100) {
      println("\"\(thing)\" is greater than one hundred.")
      isInteresting = true
    }
    if (thing > 1000) {
      println("\"\(thing)\" is greater than one thousand.")
      isInteresting = true
    }

    return isInteresting
  }
点赞