是单行if语句,或者如果没有括号不好的做法陈述? [英] Are singleline if statements or if statements without braces bad practice?

查看:985
本文介绍了是单行if语句,或者如果没有括号不好的做法陈述?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

if (condition) { /* do something */ }
else { /* do something */ }

if (condition)
    /* do something */
else
    /* do something */

我被告知,第一个例子是不是一个好主意。我不知道这是否真的是这种情况下(或第二个其一);它不能缩短量类型?还是因为它只是使一个烂摊子?

I was told that the first instance wasn't a good idea. I have no idea whether this is really this case (or for the second one either); does it not shorten the amount to type? Or is it because it just makes a mess?

推荐答案

最好的做法是写code,其他人可以读取和更新容易。

The best practice is to write code that others can read and update easily.

您第一种形式是值得怀疑的,因为它不符合大多数PHP开发人员使用的形式:

Your first form is questionable because it doesn't follow the forms that most PHP developers are used to:

if (condition) {
  // code
} else {
  // code
}

// ... or ...

if (condition)
{
  // code
}
else
{
  // code
}

// ... or ...

if (condition) { /* short code */ } else { /* short code */ }

// ... or ...

condition ? /* short code */ : /* short code */;

请注意,这完全是对标准的做法,并不一定意义—这只是什么其他的开发者都习以为常

Note that this is entirely about standard practice, and doesn't necessarily make sense—it's only about what other developers are used to seeing.

你的第二个形式,更重要的是,是不是那么好,因为它很容易让其他程序员犯这个错误:

Your second form, more importantly, isn't so good because it makes it easy for another programmer to make this mistake:

if (condition)
  // code A
else
  // code B
  // code C (added by another programmer)

在这个例子中,添加了其他程序员 code C ,却忘了整个包住其他阻止括号。这将导致的问题。你可以通过简单包装抵御这是你的如果其他在大括号块。

In this example, the other programmer added code C, but forgot to wrap the whole else block in braces. This will cause problems. You can defend against this by simply wrapping your if and else blocks in braces.

这篇关于是单行if语句,或者如果没有括号不好的做法陈述?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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