在Java中应避免使用多个if语句,例如"if(condition)if(condition)..."吗?

Lia*_*iam 5 java coding-style readability conventions

我的IDE(IntelliJ IDEA)告诉我,我可以选择删除此if语句的大括号:

if (objectIsOfTypeFoo) {
    if (objectOfTypeFooIsShared) {
        // do something with Object of type Foo knowing that it's shared...
    } else {
        // do something with Object of type Foo knowing that it's not shared...
    }
} else if (objectIsOfTypeBar) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

成为:

if (objectIsOfTypeFoo) if (objectOfTypeFooIsShared) {
    // do something with Object of type Foo knowing that it's shared...
} else {
    // do something with Object of type Foo knowing that it's not shared...
} else if (objectIsOfTypeBar) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

我理解这是有道理的,并且很容易失去缩进,但我担心的是可读性会受到影响.后者看起来更干净,但节省的空间值得潜在的混乱吗?

我认为两者之间的性能差异是微不足道的,如果有的话.

并且作为一个后续问题:是否有多少'if(条件)可以放在一行中,或者更确切地说它变得太多了?

jse*_*ano 8

我投票给你已有的方式.

我甚至不用这个:

if(foo)
   return bar;
Run Code Online (Sandbox Code Playgroud)

我喜欢这样:

if(foo){
   return bar;
}
Run Code Online (Sandbox Code Playgroud)

"必须编写程序供人们阅读,并且只有偶然的机器才能执行"

  • +1 - 确实如此,但风格和完美的报价.就个人而言,我建议你接受这个. (2认同)