【问题标题】:What is the most efficient to run certain lines of code only when a boolean is true?仅当布尔值为真时运行某些代码行最有效的是什么?
【发布时间】:2017-07-22 12:45:53
【问题描述】:

如果我的代码如下所示:

if (bool1) {
    statement1
    statement2
} else if (bool2) {
    statement3
    statement4
}

如果另一个布尔值(比如 bool3)为真,我只想运行语句 2 和 4,那么格式化它的最佳方法是什么。我知道我可以添加一个嵌套的 if 语句,但如果我有 5 个或更多 else if,从可维护性的角度来看,这似乎很糟糕。

有什么建议吗?

【问题讨论】:

  • 你可以为 bool3 设置另一个 if 条件。这是我认为最有效的,所以总共你将有 3 个 if 条件。有 5 个 if 语句是没有错的,除非很清楚理解并落入错误的陷阱。

标签: boolean boolean-logic maintainability


【解决方案1】:

至少对我来说,嵌套的 if 听起来非常好。如果没有任何语句与 bool1、bool3 和 bool4 混淆,并且您真的不想使用嵌套的 if,您可以将它们用连词放在彼此之后:

if (bool1) {
    statement1
}
if (bool1 && bool3) {
    statement2
}
if (bool2 && !bool1) {
    statement3
}
if (bool2 && !bool1 && bool3) {
    statement4
}

这看起来很糟糕,所以我只使用简单的嵌套 if。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-06
    • 1970-01-01
    • 1970-01-01
    • 2017-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多