关于如何格式化长 if 语句的愚蠢问题
对于占用多行的长 if 语句,您是否将 AND 或 OR 等条件放在新行上,如下所示:
if (something
&& something else)
或者像这样:
if (something &&
something else)
On long if statements where they take up more than one line, do you put the conditions like AND or OR on a new line like this:
if (something
&& something else)
Or like this:
if (something &&
something else)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
对于复杂的条件,请考虑将其提取到函数或变量中:
作为奖励,函数或变量的名称可用于传达条件的含义。这使您的代码更易于阅读。
For complex conditions, consider extracting it into a function or a variable:
As a bonus, the name of the function or variable can be used to communicate what the condition means. This makes your code easier to read.
我通常采用第二种方式,因为我可以排列语句。然而,在编写代码时,只要保持一致,任何一种方法都可以。
I typically do it the second way, since I can line up the statements. However, either way is fine when you're writing code, as long as you're consistent.
我更喜欢第一首的演绎。我的理由是,出于任何测试目的通过剪切/粘贴/注释删除条件更容易。注释掉一行比从上面的行中删除 and 并注释掉一行要容易得多。当我在 SQL 中执行 where 子句时,这种情况比在任何其他给定语言中的 if 语句中发生的情况更多,但很相似。
I prefer a rendition of the first. My reasoning is that deleting a condition via cut/paste/comment for any testing purposes is easier. It's a lot easier to comment out a line than it is to delete the and from the line above and comment out a line. This is more when I'm doing where clauses in SQL than in an if statement in any other given language, but is similar.
鉴于我的建议,我首先会避免进行长时间的 if 测试。我宁愿做这样的事情:
否则就是这样的事情:
YMMV,当然。
前者更容易调试、测试、记录等。
Given my druthers, I'd avoid long if tests in the first place. I'd rather do something like:
Otherwise something like this:
YMMV, of course.
The former is far easier to debug, test, log, etc.
我通常使用 IDE 格式化程序进行格式化,然后重新排列一下以使其看起来更漂亮。
I usually format using the IDE formatter and then rearrange a bit to make it look beautiful.
我在 VSC 工作,最近不仅成功地在嵌套 if 语句中编写了非常长的条件,而且使其可读。只需使用括号和新行即可。它应该自动缩进:
I'm working in VSC and recently managed to not only write, but make readable very long conditions in nested if statements. Just use brackets and new lines like this. It should make automatic indentations: