Consolidate Duplicate Conditional Fragments

Move code that is executed in all branches of a conditional outside of it.

“The same fragment of code is in all branches of a conditional expression.”

Don’t repeat yourself.

graph LR
    A[If/Else with repeated code] -->|Refactoring| B[Code moved out of If/Else]

When to apply (Smells)

  • Duplication: Same line of code at the end (or start) of both if and else blocks.

Motivation

  • DRY: Don’t Repeat Yourself.

Mechanics (Steps)

  1. Identify the duplicate code.
  2. Move it outside the conditional.

Explanation

Problem

total = price * 0.9; send(); vs total = price * 0.95; send();

Solution

Calculate total inside conditional, call send() after.

Pros and Cons

Pros Cons
  • Shorter code
  • None really
  • Code example

    Typescript

    Before

    After

    PHP

    Before

    After