使用没有花括号的 if 语句是一种不好的做法吗? [英] Is it a bad practice to use an if-statement without curly braces?

查看:39
本文介绍了使用没有花括号的 if 语句是一种不好的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过这样的代码:

if(statement)
    do this;
else
    do this;

但是,我认为这更具可读性:

However, I think this is more readable:

if(statement){
    do this;
}else{
    do this;
}

既然这两种方法都有效,那么这只是使用哪种方法的偏好问题还是推荐一种方法而不是另一种方法?

Since both methods work, is this simply a matter of preference which to use 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆