Complicated Boolean Expression


Symptoms

  • Code has complex conditions involving and , or , and not .

Causes

The code may have been complicated from the beginning, or it may have picked up additional conditions along the way.

What to Do

  • Apply DeMorgan's Law:

     ! (a && b)  => (!a)  (!b) 

    and

     !(a  b)  =>  (!a) && (!b) 

You may find that some variables will communicate better if they change names to reflect their flipped sense.

  • Introduce Explaining Variable to make each clause clearer.

  • Use guard clauses to peel off certain conditions; the remaining clauses get simpler.

  • Decompose Conditional to pull each part into its own method.

Payoff

Improves communication.

Contraindications

You may be able to find other ways to simplify the expressions, or you may find that the rewritten expression communicates less well.

Exercise 21 Conditional Expression.

Consider this code fragment:

 if (!((score > 700)     ((income >= 40000) && (income <= 100000)   && authorized && (score > 500))     (income > 100000)))    reject(); else    accept(); 
  1. Apply DeMorgan's Law to simplify this as much as possible.

  2. Starting from the original, rewrite the condition by introducing explaining variables.

  3. Starting from the original, flip the if and else clauses, then break the original into several if clauses. (You'll call accept() in three different places.)

  4. Consolidate Conditional Expression by extracting a method to compute the condition.

  5. Which approach was the simplest? The clearest? Can you combine the techniques?

  6. Describe the conditions in tabular form. Base the rows and columns on three variables: one for the three score ranges, one for the income ranges, and one for the authorized flag. The cells in the table should say either "accept" or "reject."

See Appendix A for solutions.




Refactoring Workbook
Refactoring Workbook
ISBN: 0321109295
EAN: 2147483647
Year: 2003
Pages: 146

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net