简体   繁体   English

如何在 java 中用括号将长 boolean 表达式换行

[英]How to line wrap a long boolean expression with parentheses in java

How to wrap this expression in java for more readability with the constraint that the sub expression (shouldSendSomething(x) && loooongFunctionName1(x) && looooongFunctionName2(x)) inside the paranthesis is too long to fit in a single line?如何将此表达式包装在 java 中以提高可读性,同时约束条件是括号内的子表达式(shouldSendSomething(x) && loooongFunctionName1(x) && looooongFunctionName2(x))太长而不能放在一行中?

!(loooongFunctionName0(x) && loooongFunctionName1(x) && looooongFunctionName2(x)) && looooongFunctionName3(x) && looooongFunctionName4(x) && looooongFunctionName5(x)

Maybe having each condition on a new line?也许每个条件都在新行上?

if (!(loooongFunctionName0(x) 
                && loooongFunctionName1(x) 
                && looooongFunctionName2(x)) 
                && looooongFunctionName3(x) 
                && looooongFunctionName4(x) 
                && looooongFunctionName5(x)) {
            
        }

Later Edit: If you have soo many conditions, it usually means that there is a design problem somewhere and maybe some refactoring is needed.后期编辑:如果条件太多,通常意味着某处存在设计问题,可能需要进行一些重构。

In such cases I would suggest to create some helper methods.在这种情况下,我建议创建一些辅助方法。 Wrap some of the conditions into a single method which will simplify the if condition.将一些条件包装到一个方法中,这将简化if条件。

function foo() {
  return bar && baz && qux;
}

And use it in your if condition like:并在您的if条件下使用它,例如:

if (foo()) { ... }

or或者

if (!foo()) { ... }

I personally prefer to assign the results to a meaningful & short (when possible) variable and then use it inside the if clause我个人更喜欢将结果分配给一个有意义且简短(如果可能)的变量,然后在 if 子句中使用它

boolean name0 = loooongFunctionName0(x);
boolean name1 = loooongFunctionName1(x);
boolean name2 = loooongFunctionName2(x);
boolean name3 = loooongFunctionName3(x);
boolean name4 = loooongFunctionName4(x);
boolean name5 = loooongFunctionName5(x);

if (!(name1 && name2 && name3 && name4 && name5)) {
   // something
}

According to coding standards in terms of java, max characters in one line can be 80. So here you can wrap it this way:根据 java 的编码标准,一行的最大字符数可以是 80。所以在这里你可以这样包装:

!(loooongFunctionName0(x) 
    && loooongFunctionName1(x) 
    && looooongFunctionName2(x))
&& looooongFunctionName3(x) 
&& looooongFunctionName4(x) 
&& looooongFunctionName5(x)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM