Industrial Logic Papers Extract Boolean Variable From Condition |
Extract Boolean Variable From Conditional**
MotivationComplex 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
ExampleWe 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 } |
  |
|
Facebook Twitter LinkedIn