Also known as

Refactoring Consolidate Duplicate Conditional Fragments

Problem

Identical code can be found in all branches of a conditional.

Solution

Move the code outside of the conditional.
Before
if (isSpecialDeal()) {
  total = price * 0.95;
  send();
}
else {
  total = price * 0.98;
  send();
}
After
if (isSpecialDeal()) {
  total = price * 0.95;
}
else {
  total = price * 0.98;
}
send();
Before
if (IsSpecialDeal()) 
{
  total = price * 0.95;
  Send();
}
else 
{
  total = price * 0.98;
  Send();
}
After
if (IsSpecialDeal())
{
  total = price * 0.95;
}
else
{
  total = price * 0.98;
}
Send();
Before
if (isSpecialDeal()) {
  $total = $price * 0.95;
  send();
}
else {
  $total = $price * 0.98;
  send();
}
After
if (isSpecialDeal())
  $total = $price * 0.95;
else
  $total = $price * 0.98;
send();
Before
if isSpecialDeal():
    total = price * 0.95
    send()
else:
    total = price * 0.98
    send()
After
if isSpecialDeal():
    total = price * 0.95
else:
    total = price * 0.98
send()

Why Refactor

Duplicate code is found inside all branches of a conditional, often as the result of evolution of the code within the conditional branches. Team development can be a contributing factor to this.

Benefits

  • Code deduplication.

How to Refactor

  1. If the duplicated code is at the beginning of the conditional branches, move the code to a place before the conditional.

  2. If the code is executed at the end of the branches, place it after the conditional.

  3. If the duplicate code is randomly situated inside the branches, first try to move the code to the beginning or end of the branch, depending on whether it changes the result of the subsequent code.

  4. If appropriate and the duplicate code is longer than one line, try using Extract Method.

Tired of reading?

No wonder, there are 7 hours worth of the text on this website.

Try out something different. We've just launched the interactive learning course on refactoring. It has more content and much more fun than a boring text.

Learn more...

Live Example

First time here? No worries!

Everything is quite simple. This example is like video (but much cooler):

  1. After pressing the Play button, you will see floating messages, which will guide you through the example. You can proceed by clicking on them.
  2. You can fast-forward or return to previous steps by pressing arrow buttons on the left.
  3. Also, you can take a look at the code diff window, which will show what has changed in code during the example ()
  4. To check the code for errors, you can press "Compile and test" button ()