English · PDF 305
除非后面跟着 else,否则应始终独占一行。花括号内的代码始终要缩进:
# Good if (y < 0 && debug) { message("Y is negative") } if (y == 0) { log(x) } else { y ^ x } # Bad if (y < 0 && debug) message("Y is negative") if (y == 0) { log(x) } else { y ^ x }
如果 if 语句非常短、可以放在一行内,那么省略花括号是可以接受的:
y <- 10 x <- if (y < 20) "Too low" else "Too high"
我建议仅在非常简短的 if 语句中这样做。否则,完整形式更易于阅读:
if (y < 20) { x <- "Too low" } else { x <- "Too high" }