Industrial Logic -> Papers -> Extract Boolean Variable From Condition

Extract Boolean Variable From Conditional**

You have a complicated boolean expression.

Extract part of the conditional expression and assign it to a boolean variable. Replace the conditional expression part with a reference to the boolean variable and repeat the process till the expression is no longer complex.

if ( (platform.toUpperCase().indexOf("MAC") > -1) &&
     (browser.toUpperCase().indexOf("IE") > -1) &&
      wasInitialized() && resize > 0 )
{
  // do something
}
before

boolean isMacOs     = platform.toUpperCase().indexOf("MAC") > -1;
boolean isIEBrowser = browser.toUpperCase().indexOf("IE")  > -1;
boolean wasResized  = resize > 0;

if (isMacOs && isIEBrowser && wasInitialized() && wasResized)
{
  // do something
}
after

Motivation

Complex conditional logic is tedious to read and evan harder to maintain. As many systems mature, often it is the conditional logic that shoulders the burden of increased complexity. Such complex logic smells really bad.

This situation can be remedied by converting the complex conditional logic into boolean variables and then replacing sections of the conditional expression with those boolean variables.

In this case we are choosing to use local boolean variables rather than converting them to methods using Extract Method (114). A variant on this refactoring, and one which also addresses the "then" and "else" clauses of a complex conditional, is Decompose Conditional(136).

Mechanics

  1. Replace sections of, or the entire, complex conditional expression with boolean variables.
  2. Place the boolean variables back into the conditional expression.
  3. Compile and test.

Example

We begin with our complex conditional expression.

        if ( (platform.toUpperCase().indexOf("MAC") > -1) &&
             (browser.toUpperCase().indexOf("IE") > -1) &&
              wasInitialized() && resize > 0 )
        {
          // do something
        }

Next, we extract the complex parts of the expression into booleans.

        boolean isMacOs     = platform.toUpperCase().indexOf("MAC") > -1;
  (1)   boolean isIEBrowser = browser.toUpperCase().indexOf("IE")  > -1;
        boolean wasResized  = resize > 0;

Next, we replace the old conditional expression with the new booleans.

  (2)   if (isMacOs && isIEBrowser && wasInitialized() && wasResized)
        {
          // do something
        }
Result:

boolean isMacOs     = platform.toUpperCase().indexOf("MAC") > -1;
boolean isIEBrowser = browser.toUpperCase().indexOf("IE")  > -1;
boolean wasResized  = resize > 0;

if (isMacOs && isIEBrowser && wasInitialized() && wasResized)
{
  // do something
}
  Iindustrial Logic, Inc.

 


FacebookFacebook  TwitterTwitter  linked inLinkedIn