Since Checkstyle 3.4
Restricts the number of boolean operators (&&, ||,
&, | and ^) in an expression.
Rationale: Too many conditions leads to code that is difficult to read and hence debug and maintain.
Note that the operators & and
| are not only integer bitwise operators, they are also the
non-shortcut versions of the boolean operators
&& and ||.
Note that &, | and ^ are not checked
if they are part of constructor or method call
because they can be applied to non-boolean variables and
Checkstyle does not know types of methods from different classes.
To configure the check:
<module name="Checker">
<module name="TreeWalker">
<module name="BooleanExpressionComplexity"/>
</module>
</module>
Code Example:
public class Test
{
public static void main(String ... args)
{
boolean a = true;
boolean b = false;
boolean c = (a & b) | (b ^ a); // OK, 1(&) + 1(|) + 1(^) = 3 (max allowed 3)
boolean d = (a & b) ^ (a || b) | a; // violation, 1(&) + 1(^) + 1(||) + 1(|) = 4
}
}
To configure the check with 5 allowed operation in boolean expression:
<module name="Checker">
<module name="TreeWalker">
<module name="BooleanExpressionComplexity">
<property name="max" value="5"/>
</module>
</module>
</module>
Code Example:
public class Test
{
public static void main(String ... args)
{
boolean a = true;
boolean b = false;
boolean c = (a & b) | (b ^ a) | (a ^ b); // OK, 1(&) + 1(|) + 1(^) + 1(|) + 1(^) = 5
boolean d = (a | b) ^ (a | b) ^ (a || b) & b; // violation,
// 1(|) + 1(^) + 1(|) + 1(^) + 1(||) + 1(&) = 6
}
}
To configure the check to ignore & and
|:
<module name="Checker">
<module name="TreeWalker">
<module name="BooleanExpressionComplexity">
<property name="tokens" value="BXOR,LAND,LOR"/>
</module>
</module>
</module>
Code Example:
public class Test
{
public static void main(String ... args)
{
boolean a = true;
boolean b = false;
boolean c = (!a && b) | (a || !b) ^ a; // OK, 1(&&) + 1(||) + 1(^) = 3
// | is ignored here
boolean d = a ^ (a || b) ^ (b || a) & a; // violation, 1(^) + 1(||) + 1(^) + 1(||) = 4
// & is ignored here
}
}
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks.metrics