Refactoring – decompose conditional

Complex conditional logic is tricky to debug.

It may seem obvious initially but when you land at the start with an edge case it can be a time sink hole. Especially if you keep on hitting it.

And the more and deeper nested you get the more complex it becomes.

Decompose Conditional is a simple design pattern that takes a complicated if/then/else statement and pulls it apart.

The condition is put in its own method.

And so are the then / else parts.

      if (date.before (SUMMER_START) || date.after(SUMMER_END))
          charge = quantity * _winterRate + _winterServiceCharge;
      else charge = quantity * _summerRate;

Extract the conditional and each leg as follows:

     if (notSummer(date))
          charge = winterCharge(quantity);
      else charge = summerCharge (quantity);

  private boolean notSummer(Date date) {
      return date.before (SUMMER_START) || date.after(SUMMER_END);
  }

  private double summerCharge(int quantity) {
      return quantity * _summerRate;
  }

  private double winterCharge(int quantity) {
      return quantity * _winterRate + _winterServiceCharge;
  }

Leave a Reply

Your email address will not be published. Required fields are marked *