Programming Search⌘K

Techniquecore

Extract function

Also called Extract Method.

Move a fragment of code into a function of its own, named for what the fragment does, and replace the fragment with a call. The behaviour of the program does not change.

Family
refactoring
Intent
Give a fragment of code a name that says what it does, so that the reader can skip how it does it.
Also called
Extract Method

Purpose

A long function mixes what it does with how it does it. The reader must run the code in the head to learn its purpose. Extract function moves a fragment into a function of its own and gives that function a name that states the purpose. The original function then reads as a list of steps, and the reader opens a step only when the detail matters.

Fowler gives this as his reason to extract: the separation between intention and implementation. When a reader needs effort to see what a fragment does, the fragment should become a function named for that "what".3 The rule does not depend on length. His example is a Smalltalk method highlight, whose body was only a call to reverse: the name was longer than the body, and that was the point.3 A comment above a fragment that says what it does is a common sign that the fragment wants a name.1

The refactoring changes the structure and keeps the behaviour. Tests that pass before the change must pass after it. Its inverse is Inline Function.2 The first edition of the book called the same refactoring Extract Method.11

Steps

  1. Run the tests and see them pass. Without tests that cover the fragment, the steps below have no check.
  2. Choose the fragment, and choose a name that says what it does, not how it does it.
  3. Make a function with that name, and copy the fragment into its body.
  4. Look at each variable that the fragment uses and that the source function declares. A variable that the fragment only reads becomes a parameter. A variable that the fragment declares and uses only inside itself moves into the function. A variable that the fragment assigns and the source function reads later becomes the return value.
  5. Compile, or run the type checker or linter, to find the names that the copy misses.
  6. Replace the fragment in the source function with a call, and pass the parameters and use the return value.
  7. Run the tests again.
  8. Look for other copies of the same fragment, and replace them with calls to the function.

When step 4 finds more than one assigned variable, the fragment is often the wrong size. Choose a smaller fragment, or return a small record of the values.

Example

The function invoice builds the text of an invoice. A comment marks the part that computes the total, and the expression that formats cents appears twice:

def invoice(customer, items):
    lines = [f"Invoice for {customer}"]
    for name, price, quantity in items:
        lines.append(f"  {name}: {quantity} x {price // 100}.{price % 100:02d}")
    # compute the total
    total = 0
    for _, price, quantity in items:
        total += price * quantity
    lines.append(f"Total: {total // 100}.{total % 100:02d}")
    return "\n".join(lines)


def test_invoice():
    items = [("pen", 250, 2), ("pad", 1205, 1)]
    assert invoice("Ada", items) == (
        "Invoice for Ada\n  pen: 2 x 2.50\n  pad: 1 x 12.05\nTotal: 17.05"
    )
    assert invoice("Bob", []) == "Invoice for Bob\nTotal: 0.00"


test_invoice()
print("tests pass")
print(invoice("Ada", [("pen", 250, 2), ("pad", 1205, 1)]))
Output
tests pass
Invoice for Ada
  pen: 2 x 2.50
  pad: 1 x 12.05
Total: 17.05

Two extractions follow. The block under the comment reads items and assigns total, which the function reads later, so items becomes the parameter and total becomes the return value. The function is named for the comment, and the comment goes away. The formatting expression reads one value and has no assignments, so it becomes format_cents(cents), and both copies become calls:

def format_cents(cents):
    return f"{cents // 100}.{cents % 100:02d}"


def total_cents(items):
    return sum(price * quantity for _, price, quantity in items)


def invoice(customer, items):
    lines = [f"Invoice for {customer}"]
    for name, price, quantity in items:
        lines.append(f"  {name}: {quantity} x {format_cents(price)}")
    lines.append(f"Total: {format_cents(total_cents(items))}")
    return "\n".join(lines)


def test_invoice():
    items = [("pen", 250, 2), ("pad", 1205, 1)]
    assert invoice("Ada", items) == (
        "Invoice for Ada\n  pen: 2 x 2.50\n  pad: 1 x 12.05\nTotal: 17.05"
    )
    assert invoice("Bob", []) == "Invoice for Bob\nTotal: 0.00"


def test_total_cents():
    assert total_cents([]) == 0
    assert total_cents([("pen", 250, 2)]) == 500


test_invoice()
test_total_cents()
print("tests pass")
print(invoice("Ada", [("pen", 250, 2), ("pad", 1205, 1)]))
Output
tests pass
Invoice for Ada
  pen: 2 x 2.50
  pad: 1 x 12.05
Total: 17.05

The test of invoice is the same, and it still passes. The output is the same. The extracted function total_cents can now have a test of its own.

PythonGitHub
def invoice_before(customer, items):
    lines = [f"Invoice for {customer}"]
    for name, price, quantity in items:
        lines.append(f"  {name}: {quantity} x {price // 100}.{price % 100:02d}")
    # compute the total
    total = 0
    for _, price, quantity in items:
        total += price * quantity
    lines.append(f"Total: {total // 100}.{total % 100:02d}")
    return "\n".join(lines)


def format_cents(cents):
    return f"{cents // 100}.{cents % 100:02d}"


def total_cents(items):
    return sum(price * quantity for _, price, quantity in items)


def invoice_after(customer, items):
    lines = [f"Invoice for {customer}"]
    for name, price, quantity in items:
        lines.append(f"  {name}: {quantity} x {format_cents(price)}")
    lines.append(f"Total: {format_cents(total_cents(items))}")
    return "\n".join(lines)


ITEMS = [("pen", 250, 2), ("pad", 1205, 1)]
EXPECTED = "Invoice for Ada\n  pen: 2 x 2.50\n  pad: 1 x 12.05\nTotal: 17.05"

for invoice in (invoice_before, invoice_after):
    assert invoice("Ada", ITEMS) == EXPECTED
    assert invoice("Bob", []) == "Invoice for Bob\nTotal: 0.00"
    print(f"{invoice.__name__}: tests pass")
print(invoice_after("Ada", ITEMS))
Output
invoice_before: tests pass
invoice_after: tests pass
Invoice for Ada
  pen: 2 x 2.50
  pad: 1 x 12.05
Total: 17.05
  • Verdict: idiom. The refactoring needs only a function definition. The same tests run on the code before and after the change, and both pass.
  • A fragment that assigns several variables can return a tuple, and the caller unpacks it: count, total = add_up(items).
  • A fragment that reads a variable of an enclosing function can become a nested function, which is a closure. A module-level function with parameters is clearer and can have its own tests.
  • PyCharm and the rope library do this refactoring as one command.
#include <format>
#include <iostream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>

struct Item {
    std::string name;
    int price;
    int quantity;
};

std::string invoice_before(const std::string& customer, const std::vector<Item>& items) {
    std::string text = std::format("Invoice for {}\n", customer);
    for (const auto& item : items) {
        text += std::format("  {}: {} x {}.{:02}\n", item.name, item.quantity, item.price / 100, item.price % 100);
    }
    // compute the total
    int total = 0;
    for (const auto& item : items) {
        total += item.price * item.quantity;
    }
    text += std::format("Total: {}.{:02}", total / 100, total % 100);
    return text;
}

std::string format_cents(int cents) {
    return std::format("{}.{:02}", cents / 100, cents % 100);
}

int total_cents(const std::vector<Item>& items) {
    int total = 0;
    for (const auto& item : items) {
        total += item.price * item.quantity;
    }
    return total;
}

std::string invoice_after(const std::string& customer, const std::vector<Item>& items) {
    std::string text = std::format("Invoice for {}\n", customer);
    for (const auto& item : items) {
        text += std::format("  {}: {} x {}\n", item.name, item.quantity, format_cents(item.price));
    }
    text += "Total: " + format_cents(total_cents(items));
    return text;
}

int main() {
    const std::vector<Item> items{{"pen", 250, 2}, {"pad", 1205, 1}};
    const std::string expected = "Invoice for Ada\n  pen: 2 x 2.50\n  pad: 1 x 12.05\nTotal: 17.05";
    using Invoice = std::string (*)(const std::string&, const std::vector<Item>&);
    const std::pair<const char*, Invoice> versions[] = {{"invoice_before", invoice_before},
                                                        {"invoice_after", invoice_after}};
    for (const auto& [name, invoice] : versions) {
        if (invoice("Ada", items) != expected || invoice("Bob", {}) != "Invoice for Bob\nTotal: 0.00") {
            throw std::runtime_error(std::string(name) + " failed");
        }
        std::cout << name << ": tests pass\n";
    }
    std::cout << invoice_after("Ada", items) << '\n';
}
Output
invoice_before: tests pass
invoice_after: tests pass
Invoice for Ada
  pen: 2 x 2.50
  pad: 1 x 12.05
Total: 17.05
  • Verdict: idiom. The refactoring makes a free function, or a member function when the fragment uses the members of a class.
  • Pass a value that the fragment only reads as a const reference, and return a value that it computes. A non-const reference parameter also works for a variable that the fragment changes, but it hides the data flow at the call. clangd uses a reference for such a variable when it extracts.
  • A fragment that computes two values can return a struct or a std::pair, and the caller unpacks it with a structured binding: auto [count, total] = add_up(items);.
  • A function in the same translation unit that is small can be inlined by the optimizer, so the extraction need not cost a call at run time.
JavaGitHub
import java.util.List;

public class Main {
    record Item(String name, int price, int quantity) {}

    static String invoiceBefore(String customer, List<Item> items) {
        StringBuilder text = new StringBuilder("Invoice for " + customer + "\n");
        for (Item item : items) {
            text.append(String.format("  %s: %d x %d.%02d\n",
                    item.name(), item.quantity(), item.price() / 100, item.price() % 100));
        }
        // compute the total
        int total = 0;
        for (Item item : items) {
            total += item.price() * item.quantity();
        }
        text.append(String.format("Total: %d.%02d", total / 100, total % 100));
        return text.toString();
    }

    static String formatCents(int cents) {
        return String.format("%d.%02d", cents / 100, cents % 100);
    }

    static int totalCents(List<Item> items) {
        return items.stream().mapToInt(item -> item.price() * item.quantity()).sum();
    }

    static String invoiceAfter(String customer, List<Item> items) {
        StringBuilder text = new StringBuilder("Invoice for " + customer + "\n");
        for (Item item : items) {
            text.append("  " + item.name() + ": " + item.quantity() + " x " + formatCents(item.price()) + "\n");
        }
        text.append("Total: " + formatCents(totalCents(items)));
        return text.toString();
    }

    interface Invoice {
        String make(String customer, List<Item> items);
    }

    static void check(String name, Invoice invoice) {
        List<Item> items = List.of(new Item("pen", 250, 2), new Item("pad", 1205, 1));
        String expected = "Invoice for Ada\n  pen: 2 x 2.50\n  pad: 1 x 12.05\nTotal: 17.05";
        if (!invoice.make("Ada", items).equals(expected)
                || !invoice.make("Bob", List.of()).equals("Invoice for Bob\nTotal: 0.00")) {
            throw new AssertionError(name + " failed");
        }
        System.out.println(name + ": tests pass");
    }

    public static void main(String[] args) {
        check("invoiceBefore", Main::invoiceBefore);
        check("invoiceAfter", Main::invoiceAfter);
        System.out.println(invoiceAfter("Ada", List.of(new Item("pen", 250, 2), new Item("pad", 1205, 1))));
    }
}
Output
invoiceBefore: tests pass
invoiceAfter: tests pass
Invoice for Ada
  pen: 2 x 2.50
  pad: 1 x 12.05
Total: 17.05
  • Verdict: idiom. The refactoring makes a method, usually private or static when it uses no fields.
  • A lambda can read only local variables that are effectively final, and a method cannot assign the locals of its caller. A fragment that assigns two locals must return a small record, such as record Totals(int count, int cents).
  • A fragment that uses fields of the object becomes an instance method. The fields need not become parameters, because the method can read them.
  • IntelliJ IDEA and Eclipse do Extract Method as one command.
using System.Text;

var items = new List<Item> { new("pen", 250, 2), new("pad", 1205, 1) };
var expected = "Invoice for Ada\n  pen: 2 x 2.50\n  pad: 1 x 12.05\nTotal: 17.05";
var versions = new (string Name, Func<string, List<Item>, string> Make)[]
{
    ("InvoiceBefore", Invoices.InvoiceBefore),
    ("InvoiceAfter", Invoices.InvoiceAfter),
};
foreach (var (name, make) in versions)
{
    if (make("Ada", items) != expected || make("Bob", []) != "Invoice for Bob\nTotal: 0.00")
    {
        throw new Exception($"{name} failed");
    }
    Console.WriteLine($"{name}: tests pass");
}
Console.WriteLine(Invoices.InvoiceAfter("Ada", items));

record Item(string Name, int Price, int Quantity);

static class Invoices
{
    public static string InvoiceBefore(string customer, List<Item> items)
    {
        var text = new StringBuilder($"Invoice for {customer}\n");
        foreach (var item in items)
        {
            text.Append($"  {item.Name}: {item.Quantity} x {item.Price / 100}.{item.Price % 100:D2}\n");
        }
        // compute the total
        var total = 0;
        foreach (var item in items)
        {
            total += item.Price * item.Quantity;
        }
        text.Append($"Total: {total / 100}.{total % 100:D2}");
        return text.ToString();
    }

    static string FormatCents(int cents) => $"{cents / 100}.{cents % 100:D2}";

    static int TotalCents(List<Item> items) => items.Sum(item => item.Price * item.Quantity);

    public static string InvoiceAfter(string customer, List<Item> items)
    {
        var text = new StringBuilder($"Invoice for {customer}\n");
        foreach (var item in items)
        {
            text.Append($"  {item.Name}: {item.Quantity} x {FormatCents(item.Price)}\n");
        }
        text.Append($"Total: {FormatCents(TotalCents(items))}");
        return text.ToString();
    }
}
Output
InvoiceBefore: tests pass
InvoiceAfter: tests pass
Invoice for Ada
  pen: 2 x 2.50
  pad: 1 x 12.05
Total: 17.05
  • Verdict: idiom. The refactoring makes a method, often private and static, or a local function inside the source method.
  • A fragment that assigns two locals can return a tuple, (int Count, int Total), or use out parameters.
  • Expression-bodied members (=>) suit a short extracted method such as FormatCents.
  • Visual Studio has Extract Method as one command.
JavaScriptGitHub
import assert from "node:assert/strict";

function invoiceBefore(customer, items) {
  const lines = [`Invoice for ${customer}`];
  for (const [name, price, quantity] of items) {
    lines.push(`  ${name}: ${quantity} x ${Math.trunc(price / 100)}.${String(price % 100).padStart(2, "0")}`);
  }
  // compute the total
  let total = 0;
  for (const [, price, quantity] of items) {
    total += price * quantity;
  }
  lines.push(`Total: ${Math.trunc(total / 100)}.${String(total % 100).padStart(2, "0")}`);
  return lines.join("\n");
}

function formatCents(cents) {
  return `${Math.trunc(cents / 100)}.${String(cents % 100).padStart(2, "0")}`;
}

function totalCents(items) {
  return items.reduce((sum, [, price, quantity]) => sum + price * quantity, 0);
}

function invoiceAfter(customer, items) {
  const lines = [`Invoice for ${customer}`];
  for (const [name, price, quantity] of items) {
    lines.push(`  ${name}: ${quantity} x ${formatCents(price)}`);
  }
  lines.push(`Total: ${formatCents(totalCents(items))}`);
  return lines.join("\n");
}

const items = [["pen", 250, 2], ["pad", 1205, 1]];
const expected = "Invoice for Ada\n  pen: 2 x 2.50\n  pad: 1 x 12.05\nTotal: 17.05";

for (const invoice of [invoiceBefore, invoiceAfter]) {
  assert.equal(invoice("Ada", items), expected);
  assert.equal(invoice("Bob", []), "Invoice for Bob\nTotal: 0.00");
  console.log(`${invoice.name}: tests pass`);
}
console.log(invoiceAfter("Ada", items));
Output
invoiceBefore: tests pass
invoiceAfter: tests pass
Invoice for Ada
  pen: 2 x 2.50
  pad: 1 x 12.05
Total: 17.05
  • Verdict: idiom. A function declaration is enough. The same checks run on both versions.
  • A fragment that assigns several variables can return an object or an array, and the caller destructures it: const { count, total } = addUp(items);.
  • A fragment that uses this must become a method, or take the object as a parameter. An arrow function keeps the this of the place where it is defined.
  • Visual Studio Code offers "Extract to function" through the TypeScript language service, for JavaScript files too.
TypeScriptGitHub
import assert from "node:assert/strict";

type Item = readonly [name: string, price: number, quantity: number];

function invoiceBefore(customer: string, items: readonly Item[]): string {
  const lines = [`Invoice for ${customer}`];
  for (const [name, price, quantity] of items) {
    lines.push(`  ${name}: ${quantity} x ${Math.trunc(price / 100)}.${String(price % 100).padStart(2, "0")}`);
  }
  // compute the total
  let total = 0;
  for (const [, price, quantity] of items) {
    total += price * quantity;
  }
  lines.push(`Total: ${Math.trunc(total / 100)}.${String(total % 100).padStart(2, "0")}`);
  return lines.join("\n");
}

function formatCents(cents: number): string {
  return `${Math.trunc(cents / 100)}.${String(cents % 100).padStart(2, "0")}`;
}

function totalCents(items: readonly Item[]): number {
  return items.reduce((sum, [, price, quantity]) => sum + price * quantity, 0);
}

function invoiceAfter(customer: string, items: readonly Item[]): string {
  const lines = [`Invoice for ${customer}`];
  for (const [name, price, quantity] of items) {
    lines.push(`  ${name}: ${quantity} x ${formatCents(price)}`);
  }
  lines.push(`Total: ${formatCents(totalCents(items))}`);
  return lines.join("\n");
}

const items: Item[] = [["pen", 250, 2], ["pad", 1205, 1]];
const expected = "Invoice for Ada\n  pen: 2 x 2.50\n  pad: 1 x 12.05\nTotal: 17.05";

for (const invoice of [invoiceBefore, invoiceAfter]) {
  assert.equal(invoice("Ada", items), expected);
  assert.equal(invoice("Bob", []), "Invoice for Bob\nTotal: 0.00");
  console.log(`${invoice.name}: tests pass`);
}
console.log(invoiceAfter("Ada", items));
Output
invoiceBefore: tests pass
invoiceAfter: tests pass
Invoice for Ada
  pen: 2 x 2.50
  pad: 1 x 12.05
Total: 17.05
  • Verdict: idiom. The refactoring is the same as in JavaScript, and the extracted function gets parameter and return types.
  • The types are a check of step 5. If the extracted function misses a parameter, the name is not in scope and the type checker reports it before any test runs.
  • The type alias Item names the tuple once, so the source function and the extracted function share it.
  • The TypeScript language service, used by Visual Studio Code, offers "Extract to function in module scope" and other targets for the extracted code.
package main

import (
	"fmt"
	"strings"
)

type Item struct {
	Name     string
	Price    int
	Quantity int
}

func invoiceBefore(customer string, items []Item) string {
	var b strings.Builder
	fmt.Fprintf(&b, "Invoice for %s\n", customer)
	for _, item := range items {
		fmt.Fprintf(&b, "  %s: %d x %d.%02d\n", item.Name, item.Quantity, item.Price/100, item.Price%100)
	}
	// compute the total
	total := 0
	for _, item := range items {
		total += item.Price * item.Quantity
	}
	fmt.Fprintf(&b, "Total: %d.%02d", total/100, total%100)
	return b.String()
}

func formatCents(cents int) string {
	return fmt.Sprintf("%d.%02d", cents/100, cents%100)
}

func totalCents(items []Item) int {
	total := 0
	for _, item := range items {
		total += item.Price * item.Quantity
	}
	return total
}

func invoiceAfter(customer string, items []Item) string {
	var b strings.Builder
	fmt.Fprintf(&b, "Invoice for %s\n", customer)
	for _, item := range items {
		fmt.Fprintf(&b, "  %s: %d x %s\n", item.Name, item.Quantity, formatCents(item.Price))
	}
	fmt.Fprintf(&b, "Total: %s", formatCents(totalCents(items)))
	return b.String()
}

func main() {
	items := []Item{{"pen", 250, 2}, {"pad", 1205, 1}}
	expected := "Invoice for Ada\n  pen: 2 x 2.50\n  pad: 1 x 12.05\nTotal: 17.05"
	versions := []struct {
		name    string
		invoice func(string, []Item) string
	}{{"invoiceBefore", invoiceBefore}, {"invoiceAfter", invoiceAfter}}
	for _, v := range versions {
		if v.invoice("Ada", items) != expected || v.invoice("Bob", nil) != "Invoice for Bob\nTotal: 0.00" {
			panic(v.name + " failed")
		}
		fmt.Println(v.name + ": tests pass")
	}
	fmt.Println(invoiceAfter("Ada", items))
}
Output
invoiceBefore: tests pass
invoiceAfter: tests pass
Invoice for Ada
  pen: 2 x 2.50
  pad: 1 x 12.05
Total: 17.05
  • Verdict: idiom. The refactoring makes a function, or a method when the fragment uses a receiver.
  • Go functions return several values, so a fragment that assigns two variables can return both: count, total := addUp(items).
  • The usual test is a _test.go file that runs under go test. This page checks both versions in main so that the block runs on its own.
  • gopls offers the code actions refactor.extract.function and refactor.extract.method for a selection of statements.
RustGitHub
struct Item {
    name: &'static str,
    price: u32,
    quantity: u32,
}

fn invoice_before(customer: &str, items: &[Item]) -> String {
    let mut lines = vec![format!("Invoice for {customer}")];
    for item in items {
        lines.push(format!(
            "  {}: {} x {}.{:02}",
            item.name,
            item.quantity,
            item.price / 100,
            item.price % 100
        ));
    }
    // compute the total
    let mut total = 0;
    for item in items {
        total += item.price * item.quantity;
    }
    lines.push(format!("Total: {}.{:02}", total / 100, total % 100));
    lines.join("\n")
}

fn format_cents(cents: u32) -> String {
    format!("{}.{:02}", cents / 100, cents % 100)
}

fn total_cents(items: &[Item]) -> u32 {
    items.iter().map(|item| item.price * item.quantity).sum()
}

fn invoice_after(customer: &str, items: &[Item]) -> String {
    let mut lines = vec![format!("Invoice for {customer}")];
    for item in items {
        lines.push(format!("  {}: {} x {}", item.name, item.quantity, format_cents(item.price)));
    }
    lines.push(format!("Total: {}", format_cents(total_cents(items))));
    lines.join("\n")
}

fn main() {
    let items = [
        Item { name: "pen", price: 250, quantity: 2 },
        Item { name: "pad", price: 1205, quantity: 1 },
    ];
    let expected = "Invoice for Ada\n  pen: 2 x 2.50\n  pad: 1 x 12.05\nTotal: 17.05";
    let versions: [(&str, fn(&str, &[Item]) -> String); 2] =
        [("invoice_before", invoice_before), ("invoice_after", invoice_after)];
    for (name, invoice) in versions {
        assert_eq!(invoice("Ada", &items), expected);
        assert_eq!(invoice("Bob", &[]), "Invoice for Bob\nTotal: 0.00");
        println!("{name}: tests pass");
    }
    println!("{}", invoice_after("Ada", &items));
}
Output
invoice_before: tests pass
invoice_after: tests pass
Invoice for Ada
  pen: 2 x 2.50
  pad: 1 x 12.05
Total: 17.05
  • Verdict: idiom. The refactoring makes a function. The borrow checker decides how each variable can pass: &[Item] for a value that the fragment reads, &mut for one that it changes, or by value for one that it consumes.
  • A fragment that assigns two variables can return a tuple: let (count, total) = add_up(&items);.
  • The usual tests are #[test] functions in a #[cfg(test)] module. This page checks both versions in main so that the block runs as one program.
  • rust-analyzer has the assist extract_function, which finds the parameters and the return value.

When to use

  • A reader needs effort to see what a fragment does, or a comment explains what a fragment does.
  • The same fragment appears in more than one place.
  • A function does several steps at different levels of detail, such as a computation, formatting and output in one body.
  • Another refactoring needs a smaller function first, for example to move behaviour to another class or to replace a conditional.

Do not extract when no name says more than the code does. A function add_one(x) with the body x + 1 adds a jump and no meaning. Fowler notes that short functions work only when the names are good.3

Pitfalls

A lost assignment. If the fragment assigns a local variable that the source function reads later, the extracted function must return the value. In Python, Java, JavaScript and Go, an assignment to a parameter changes the parameter only, not the variable of the caller:

This code runs but gives a wrong answer on purpose.

def summary(items):
    count = 0
    total = 0
    for _, price, quantity in items:
        count += quantity
        total += price * quantity
    return f"{count} items, {total} cents"


def add_up(items, count, total):  # extracted by hand, with a mistake
    for _, price, quantity in items:
        count += quantity
        total += price * quantity


def summary_after(items):
    count = 0
    total = 0
    add_up(items, count, total)
    return f"{count} items, {total} cents"


items = [("pen", 250, 2), ("pad", 1205, 1)]
print("before:", summary(items))
print("after: ", summary_after(items))
Output
before: 3 items, 1705 cents
after:  0 items, 0 cents

The fix is to return the values: count, total = add_up(items). A test of summary_after finds the mistake at once. In C++ and Rust, the same fragment can take a reference (int&, &mut i64), but a return value keeps the data flow visible at the call.

Control flow that leaves the fragment. A return, break or continue inside the fragment leaves the source function or its loop. After the extraction, it leaves only the extracted function. Move such a statement out of the fragment first, or make the function return a value that the caller tests. Refactoring tools often refuse such a fragment.

Too many parameters. A fragment that reads seven local variables gives a function with seven parameters. Other refactorings of the catalog help first: Replace Temp with Query removes a local variable, Introduce Parameter Object groups values that travel together, and Replace Function with Command turns the function into an object with fields.1

A name that says how. A name such as loop_over_items restates the code. The reader still has to read the body. Name the result or the purpose: total_cents.

Fear of the cost of the call. Fowler writes that the cost of a function call was occasionally a factor in his early career and is now very rare.3 Compilers and JIT compilers often inline small functions. Measure before you keep a long function for speed.

Tools that do it

Many editors and language servers do this refactoring as one command. The tool finds the parameters and the return value, makes the function and replaces the fragment, and it refuses a fragment that it cannot extract safely.

  • IntelliJ IDEA (for Java) and PyCharm (for Python) have the refactoring Extract Method.45
  • Visual Studio has Extract Method for C#.6
  • Visual Studio Code, through the TypeScript language service, has the code action "Extract to method or function" for JavaScript and TypeScript.7
  • gopls, the Go language server, has the code actions refactor.extract.function and refactor.extract.method.8
  • rust-analyzer has the assist extract_function.9
  • clangd, the C and C++ language server, has an ExtractFunction tweak. It extracts statements from a function that is not a template, and it passes a variable that the fragment changes by non-const reference.10

A tool can prove that the extraction keeps the behaviour only for the facts it checks. Run the tests after the tool too.

References

  1. Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 6, A First Set of Refactorings, Extract Function (page 106), motivation and mechanics
  2. Martin Fowler, Catalog of Refactorings, Extract Function, the entry; formerly Extract Method; inverse of Inline Function
  3. Martin Fowler, Function Length, bliki, 30 November 2016, intention and implementation; the highlight and reverse example; the cost of a function call
  4. IntelliJ IDEA documentation, Extract method, the refactoring and its options
  5. PyCharm documentation, Extract method, the refactoring
  6. Visual Studio documentation, Extract method refactoring, the refactoring for C# and Visual Basic
  7. Visual Studio Code documentation, Refactoring TypeScript and JavaScript, Extract to method or function
  8. gopls documentation, Code transformation features, the code action kinds refactor.extract.function and refactor.extract.method
  9. rust-analyzer manual, Assists, extract_function
  10. LLVM project source at llvmorg-21.1.0, clangd tweak ExtractFunction, the file header comment, lines 9 to 30
  11. Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 6, Composing Methods, Extract Method

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/EKDK97/text.yaml