SimplifyBooleanExpression

Since Checkstyle 3.0

Description

Checks for over-complicated boolean expressions. Currently, it finds code like if (b == true), b || true, !false, boolean a = q > 12 ? true : false, etc.

Rationale: Complex boolean logic makes code hard to understand and maintain.

Examples

To configure the check:

<module name="Checker">
  <module name="TreeWalker">
    <module name="SimplifyBooleanExpression"/>
  </module>
</module>
        

Example:

class Example1 {
  void InvalidExample() {
    boolean a=true;
    boolean b=true;
    Object c=null;
    Object d=null;
    Object e=null;
    if (!false) {}; // violation, can be simplified to true
    if (a == true) {}; // violation, can be simplified to a
    if (a == b) {};
    if (a == false) {}; // violation, can be simplified to !a
    if (!(a != true)) {}; // violation, can be simplified to a
    e = (a || b) ? c : d;
    e = (a || false) ? c : d; // violation, can be simplified to a
    e = (a && b) ? c : d;
    int s = 12;
    boolean m = s > 1 ? true : false; // violation, can be simplified to s > 1
    boolean f = c == null ? false : c.equals(d);
  }
}
        

Example of Usage

Violation Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker