Class SimplifyBooleanExpressionCheck

  • All Implemented Interfaces:
    Configurable, Contextualizable

    public class SimplifyBooleanExpressionCheck
    extends AbstractCheck

    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.

    To configure the check:

     <module name="SimplifyBooleanExpression"/>
     

    Example:

     public class Test {
    
       public void bar() {
    
         boolean a, b;
         Foo c, d, e;
    
         if (!false) {};       // violation, can be simplified to true
    
         if (a == true) {};    // violation, can be simplified to a
         if (a == b) {};       // OK
         if (a == false) {};   // violation, can be simplified to !a
         if (!(a != true)) {}; // violation, can be simplified to a
    
         e = (a || b) ? c : d;     // OK
         e = (a || false) ? c : d; // violation, can be simplified to a
         e = (a && b) ? c : d;     // OK
    
         int s = 12;
         boolean m = s > 1 ? true : false; // violation, can be simplified to s > 1
         boolean f = c == null ? false : c.someMethod(); // OK
      }
    
     }
     

    Parent is com.puppycrawl.tools.checkstyle.TreeWalker

    Violation Message Keys:

    • simplify.expression
    Since:
    3.0