使用没有花括号的if语句是不好的做法吗? [英] Is it a bad practice to use an if-statement without curly braces?
问题描述
我见过这样的代码:
if(statement)
do this;
else
do this;
我不喜欢这样,我认为这更清晰,更具可读性
I don't like that, I think this is cleaner and more readable
if(statement){
do this;
}else{
do this;
}
这只是一个偏好问题,还是会推荐一种方式优于另一种方式?
Is this simply a matter of preference or would one way be recommended over the other?
推荐答案
第一个版本的问题是,如果你返回并在if或else子句中添加第二个语句而没有记住要添加花括号,你的代码会以意想不到的方式打破。
The problem with the first version is that if you go back and add a second statement to the if or else clauses without remembering to add the curly braces, your code will break in unexpected and amusing ways.
可维护性,使用第二个总是更聪明形式。
Maintainability-wise, it's always smarter to use the second form.
编辑:Ned在评论中指出了这一点,但我认为值得链接到这里。这不仅仅是一些象牙塔假设的废话: https://www.imperialviolet。 org / 2014/02/22 / applebug.html
Ned points this out in the comments, but it's worth linking to here, too, I think. This is not just some ivory-tower hypothetical bullshit: https://www.imperialviolet.org/2014/02/22/applebug.html
这篇关于使用没有花括号的if语句是不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!