使用多行“ands”或“ors”格式化Java中的“if”语句的正确方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19825746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the proper way to format "if" statements in Java with multiline "ands" or "ors"?
提问by Dasmowenator
Apparently "if", "and", and "or" are such generic search parameters that I can't find the answer on google for my life. Which of these is the correct format according to the Java standards?
显然,“如果”、“和”和“或”是如此通用的搜索参数,以至于我一生都无法在谷歌上找到答案。根据 Java 标准,以下哪种格式是正确的?
Option 1:
选项 1:
if (condition1
&& condition2
&& condition3) ...
or Option 2:
或选项2:
if (condition1 &&
condition2 &&
condition3) ...
采纳答案by Dawood ibn Kareem
The Oracle/Sun guidelines ("Code Conventions for the Java TM Programming Language") tell us to break before an operator. And they give this example.
Oracle/Sun 指南(“Java TM 编程语言的代码约定”)告诉我们在操作符之前中断。他们举了这个例子。
if ((condition1 && condition2)
|| (condition3 && condition4)
||!(condition5 && condition6)) {
doSomethingAboutIt();
}
Many companies that I've worked for adopt the Oracle/Sun guidelines as the standard for their own code.
我工作过的许多公司都采用 Oracle/Sun 准则作为他们自己代码的标准。
Refer http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-136091.html#248
参考http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-136091.html#248
回答by yamafontes
This is a preference question. But usually you want to follow the style guidelines of either your company or whoever else is working on the codebase with you. As long as it's consistent, any style is fine.
这是一个偏好问题。但通常您希望遵循您公司或与您一起处理代码库的任何其他人的风格指南。只要是一致的,任何风格都可以。
Personally, I'd keep everything on the same line. (ever dealt with tabs vs. spaces?)
就个人而言,我会将所有内容都放在同一条线上。(曾经处理过制表符还是空格?)
However, if you have enough conditions to fill multiple lines, you should probably break your problem into smaller pieces.
但是,如果您有足够的条件来填充多行,您可能应该将问题分解为更小的部分。
回答by MadConan
This is completely subjective. Coding standards vary from shop to shop. To steal from yshavit's comment: Do whatever you want unless you are working in a team environment, in which case you should follow the team standards.
这是完全主观的。编码标准因商店而异。从 yshavit 的评论中窃取:做任何你想做的事,除非你在团队环境中工作,在这种情况下,你应该遵循团队标准。
I'm a fan of the second pattern.
我是第二种模式的粉丝。
回答by Xuan
I believe the correct answer is <CTRL>+<SHIFT>+F
in Eclipse :)
我相信正确的答案是<CTRL>+<SHIFT>+F
在 Eclipse 中 :)