SN

March 21, 2018

Refactoring: Extract Method

The main reason for writing tests is that they give us the confidence to refactor our code.

Since that’s the case, I thought I’d go through each of the refactoring techniques in Martin Fowler’s book, Refactoring .

I’ll start with Extract Method, because it is a step that shows up in almost all other refactoring techniques, and it is the source of most of the problems in our code.

Almost all the time the problems come from methods that are too long. Long methods are troublesome because they often contain lots of information, which gets buried by the complex logic that usually gets dragged in.

- Martin Fowler

With Extract Method we’re taking a long method, and breaking it into smaller, well named methods. Small methods are easier to understand, they tend to be less error prone, and they are more likely to be reusable.

Let’s say we want to see how much a customer owes.

public function showBill($amount, $tax)
{
    $this->doSomething();

    // display bill
    echo "Subtotal: " . $amount;
    echo "Tax: " . $tax;
    echo "Total: " . $amount + $tax;
}

Instead, let’s group all of the code underneath of the “display bill” comment into it’s own method.

public function showBill($amount, $tax)
{
    $this->doSomething();
    $this->displayDetails($amount, $tax);
}

public function displayDetails($amount, $tax)
{
    echo "Subtotal: " . $amount;
    echo "Tax: " . $tax;
    echo "Total: " . $amount + $tax;
}

I know this example is simplistic, but at scale this technique will greatly improve the readability of the code.

Here’s a guideline I use.

If I see a method that is over 10 lines long, I use it as an indicator that some logic might need to be extracted into another method.

In the next Refactoring post I’ll go over Replace Method with Method Object, which is a technique for extracting a method that has many local variables.

Are you new to Test Driven Development?

Join the mailing list! :)