Decompose Conditional

Decompose the complicated parts of a conditional if-then-else into separate methods.

“You have a complicated conditional (if-then-else) statement.”

Extract methods from if, then, and else blocks.

graph LR
    A[Copmlex If/Then/Else] -->|Refactoring| B[Simple If/Then/Else with Method Calls]

When to apply (Smells)

  • Long Method: Large blocks inside conditionals.
  • Complex Conditionals: The condition itself (a > b && c < d || ...) is hard to read.

Motivation

  • Readability: Makes the logic obvious. if (isSummer()) chargeSummerRate(); else chargeWinterRate();

Mechanics (Steps)

  1. Extract the condition into a boolean method (e.g., isSummer()).
  2. Extract the “then” part into a method.
  3. Extract the “else” part into a method.

Explanation

Problem

You have complex conditionals. if (date.before(SUMMER_START) || date.after(SUMMER_END)) charge = quantity * winterRate + serviceCharge; else charge = quantity * summerRate;

Solution

Extract methods.

Pros and Cons

Pros Cons
  • Readability
  • More methods
  • Code example

    Typescript

    Before

    After

    PHP

    Before

    After