Programming Search⌘K

Patterncore

Long Function

Also called long method, large function.

A code smell: a function does so many steps that a reader must study its body to know what it does, and the steps cannot be tested or reused one at a time.

Family
code-smell
Intent
Find the functions whose body hides their purpose, and split them into smaller functions whose names say what each step does.
Also called
Long Method

Intent

Find the functions that a reader must read line by line to understand, and split them into steps with names. Then the reader of the top function sees what it does, and goes into a step only to see how.

Problem

A long function does many things in sequence: it reads input, checks it, computes, formats and writes. Each part may be correct, but the reader must hold all of them in mind to know what the function does as a whole, and to know which local variable is used where.

The forces are these:

  • Length is a sign, not the problem. Fowler calls the question of function length "a proxy for the more important question - when should we enclose code in its own function?" His answer is "the separation between intention and implementation": "If you have to spend effort into looking at a fragment of code to figure out what it's doing, then you should extract it into a function and name the function after that “what”."1
  • So a short function can be worth a name. Fowler tells of a Smalltalk method highlight whose body was one call to reverse. The name was longer than the body, and it was still right, because it said the intent.1
  • A long function is hard to test in parts. A test can call the whole function only, so each test must set up all the inputs, even to check one step.
  • People resist small functions because of the cost of a call. Fowler writes that this was "occasionally a factor" when he was young, but that such cases are very rare, and that optimizing compilers often work better with shorter functions.1

Refactoring calls the smell Long Method in the first edition and Long Function in the second, which moves from Java to JavaScript and is less centred on objects.234

Solution

Most of the time the fix is Extract Function: find a part of the function that goes together, move it to a function of its own, and give it a name that says what it does.3 In the second edition, Extract Method of the first edition became Extract Function.4

Refactoring gives cues that show where to cut.3

  1. A comment. A comment that explains the next block of code is a name waiting for a function. Extract the block, and use the comment as the name.
  2. A conditional. Use Decompose Conditional to give the condition and each branch a function.
  3. A loop. Extract the loop and its body. If one loop does two jobs, use Split Loop first, so that each loop does one job.
  4. A switch on a type. When the same switch appears in other functions too, use Replace Conditional with Polymorphism.

The extracted parts often need many of the local variables of the long function, so the calls get long parameter lists. Refactoring gives three ways to reduce them: Replace Temp with Query turns a temporary variable into a function call; Introduce Parameter Object and Preserve Whole Object pass one value in place of many. When a function still has too many shared variables, Replace Function with Command turns it into an object, and the variables become fields that each step can read.3 Each of these refactorings has a card in the online catalogue.5

Example

The function computes the text of an invoice. It adds up the lines, gives a 10% discount at 100.00 or more, adds 20% tax on the discounted amount and formats the result. Comments mark the steps. All amounts are whole cents, so the arithmetic is exact.

import assert from "node:assert/strict";

// Before: one function, with comments for the steps.
function invoiceBefore(order) {
  // add up the lines
  let subtotal = 0;
  for (const line of order.lines) subtotal += line.price * line.qty;
  // discount for large orders
  let discount = 0;
  if (subtotal >= 10000) discount = Math.round(subtotal / 10);
  // tax on the discounted amount
  const tax = Math.round((subtotal - discount) / 5);
  // format
  const total = subtotal - discount + tax;
  return `${order.customer}: ${(total / 100).toFixed(2)}`;
}

// After: each comment became the name of a function.
const subtotal = (lines) => lines.reduce((sum, l) => sum + l.price * l.qty, 0);
const discount = (cents) => (cents >= 10000 ? Math.round(cents / 10) : 0);
const tax = (cents) => Math.round(cents / 5);
const formatCents = (cents) => (cents / 100).toFixed(2);

function invoice(order) {
  const gross = subtotal(order.lines);
  const net = gross - discount(gross);
  return `${order.customer}: ${formatCents(net + tax(net))}`;
}

const large = { customer: "Ada", lines: [{ price: 4000, qty: 2 }, { price: 2500, qty: 1 }] };
const small = { customer: "Bob", lines: [{ price: 1500, qty: 2 }] };
for (const f of [invoiceBefore, invoice]) {
  assert.equal(f(large), "Ada: 113.40");
  assert.equal(f(small), "Bob: 36.00");
  assert.equal(discount(9999), 0);
  console.log(`${f.name}: tests pass`);
}
Output
invoiceBefore: tests pass
invoice: tests pass

For the large order, the subtotal is 105.00, the discount is 10.50, the tax is 20% of 94.50, which is 18.90, and the total is 113.40. The "after" version reads as the rule itself: the net amount is the gross amount less the discount, and the total is the net amount plus tax. Each step can now be tested alone, as the test of discount(9999) shows.

Language What the example shows
JavaScript the split above, with arrow functions for the steps
Python the same split, with sum over a generator for the subtotal
Java the split into private static methods, with a record for each line
Go the split into unexported functions, with fmt.Sprintf for the format
PythonGitHub
# Before: one function, with comments for the steps.
def invoice_before(order):
    # add up the lines
    subtotal = 0
    for line in order["lines"]:
        subtotal += line["price"] * line["qty"]
    # discount for large orders
    discount = 0
    if subtotal >= 10000:
        discount = round(subtotal / 10)
    # tax on the discounted amount
    tax = round((subtotal - discount) / 5)
    # format
    total = subtotal - discount + tax
    return f"{order['customer']}: {total / 100:.2f}"


# After: each comment became the name of a function.
def subtotal(lines):
    return sum(line["price"] * line["qty"] for line in lines)


def discount(cents):
    return round(cents / 10) if cents >= 10000 else 0


def tax(cents):
    return round(cents / 5)


def format_cents(cents):
    return f"{cents / 100:.2f}"


def invoice(order):
    gross = subtotal(order["lines"])
    net = gross - discount(gross)
    return f"{order['customer']}: {format_cents(net + tax(net))}"


large = {"customer": "Ada", "lines": [{"price": 4000, "qty": 2}, {"price": 2500, "qty": 1}]}
small = {"customer": "Bob", "lines": [{"price": 1500, "qty": 2}]}
for f in (invoice_before, invoice):
    assert f(large) == "Ada: 113.40"
    assert f(small) == "Bob: 36.00"
    assert discount(9999) == 0
    print(f"{f.__name__}: tests pass")
Output
invoice_before: tests pass
invoice: tests pass
  • Python's round rounds a half to the even neighbour, and JavaScript's Math.round rounds a half up. The amounts in the test divide exactly, so both give the same result. A real invoice must choose one rule and use it in one place, which the extracted discount and tax make possible.
  • The local variable subtotal in the "before" version and the function subtotal in the "after" version have the same name. Inside the long function, the variable hides the function, which is one reason to extract before the names collide.
JavaGitHub
import java.util.List;
import java.util.Locale;

public class Main {
    record Line(long price, int qty) {}
    record Order(String customer, List<Line> lines) {}

    // Before: one method, with comments for the steps.
    static String invoiceBefore(Order order) {
        // add up the lines
        long subtotal = 0;
        for (Line line : order.lines()) subtotal += line.price() * line.qty();
        // discount for large orders
        long discount = 0;
        if (subtotal >= 10000) discount = Math.round(subtotal / 10.0);
        // tax on the discounted amount
        long tax = Math.round((subtotal - discount) / 5.0);
        // format
        long total = subtotal - discount + tax;
        return order.customer() + ": " + String.format(Locale.ROOT, "%.2f", total / 100.0);
    }

    // After: each comment became the name of a method.
    private static long subtotal(List<Line> lines) {
        return lines.stream().mapToLong(l -> l.price() * l.qty()).sum();
    }

    private static long discount(long cents) {
        return cents >= 10000 ? Math.round(cents / 10.0) : 0;
    }

    private static long tax(long cents) { return Math.round(cents / 5.0); }

    private static String formatCents(long cents) {
        return String.format(Locale.ROOT, "%.2f", cents / 100.0);
    }

    static String invoice(Order order) {
        long gross = subtotal(order.lines());
        long net = gross - discount(gross);
        return order.customer() + ": " + formatCents(net + tax(net));
    }

    interface Invoice { String of(Order order); }

    static void check(String name, Invoice f) {
        Order large = new Order("Ada", List.of(new Line(4000, 2), new Line(2500, 1)));
        Order small = new Order("Bob", List.of(new Line(1500, 2)));
        if (!f.of(large).equals("Ada: 113.40") || !f.of(small).equals("Bob: 36.00") || discount(9999) != 0) {
            throw new AssertionError(name);
        }
        System.out.println(name + ": tests pass");
    }

    public static void main(String[] args) {
        check("invoiceBefore", Main::invoiceBefore);
        check("invoice", Main::invoice);
    }
}
Output
invoiceBefore: tests pass
invoice: tests pass
  • String.format uses the default locale, which can print a comma as the decimal mark. Locale.ROOT fixes the format, and in the "after" version the fix is in one method.
  • subtotal / 10 with two long values would truncate, so the code divides by 10.0 and rounds with Math.round.
package main

import (
	"fmt"
	"math"
)

type line struct{ price, qty int }

type order struct {
	customer string
	lines    []line
}

// Before: one function, with comments for the steps.
func invoiceBefore(o order) string {
	// add up the lines
	subtotal := 0
	for _, l := range o.lines {
		subtotal += l.price * l.qty
	}
	// discount for large orders
	discount := 0
	if subtotal >= 10000 {
		discount = int(math.Round(float64(subtotal) / 10))
	}
	// tax on the discounted amount
	tax := int(math.Round(float64(subtotal-discount) / 5))
	// format
	total := subtotal - discount + tax
	return fmt.Sprintf("%s: %.2f", o.customer, float64(total)/100)
}

// After: each comment became the name of a function.
func subtotal(lines []line) int {
	sum := 0
	for _, l := range lines {
		sum += l.price * l.qty
	}
	return sum
}

func discount(cents int) int {
	if cents < 10000 {
		return 0
	}
	return int(math.Round(float64(cents) / 10))
}

func tax(cents int) int { return int(math.Round(float64(cents) / 5)) }

func formatCents(cents int) string { return fmt.Sprintf("%.2f", float64(cents)/100) }

func invoice(o order) string {
	gross := subtotal(o.lines)
	net := gross - discount(gross)
	return o.customer + ": " + formatCents(net+tax(net))
}

func main() {
	large := order{"Ada", []line{{4000, 2}, {2500, 1}}}
	small := order{"Bob", []line{{1500, 2}}}
	for _, v := range []struct {
		name string
		f    func(order) string
	}{{"invoiceBefore", invoiceBefore}, {"invoice", invoice}} {
		if v.f(large) != "Ada: 113.40" || v.f(small) != "Bob: 36.00" || discount(9999) != 0 {
			panic(v.name)
		}
		fmt.Println(v.name + ": tests pass")
	}
}
Output
invoiceBefore: tests pass
invoice: tests pass
  • In the "before" version, the local variables subtotal, discount and tax hide the package functions with the same names. Go allows this, but after the declaration the code in the function cannot call the function tax, because the name means the variable. The extract removes the clash.
  • discount uses an early return for the small case. Each extracted function is short enough that its control flow fits in a few lines.

Consequences

The top function becomes short, and reads like a list of steps. The steps get names that a test, a stack trace and a search can use. A step that two functions need can be shared, which is one of the fixes for Duplicated Code.

The cost is more names and more jumps. A reader who wants the whole detail must follow the calls. Fowler's answer is that the names must be good: "Small functions like this only work if the names are good".1 A step with a bad name is worse than the same lines inline.

There is no agreed number of lines. Fowler writes that "Any function more than half-a-dozen lines of code starts to smell to me", and that half of the methods in the Ruby code of his website, about 15 KLOC, are two lines or less.1 The default limits of linters are much higher:

Tool Rule Default limit
ESLint max-lines-per-function 50 lines6
ESLint max-statements 10 statements7
Checkstyle MethodLength 150 lines, with blank lines and comments counted8
Pylint max-statements 50 statements9
golangci-lint funlen 60 lines and 40 statements10

A linter limit finds the worst cases. It cannot find a ten-line function that does two things, and it can push a programmer to split a function at a point that has no meaning, only to get under the limit.

How to fix it

Run the tests after each step. Each extract is small, so a failing test points to the last change.

Large Class. The same smell one level up: a class with too many fields and methods. See Large Class.

Long Parameter List. A long function is often called with many arguments, and splitting it can make the parameter lists of the parts long. See Long Parameter List.

Comments. A comment that explains a block is one of the cues for Extract Function. See Comments.

Too many branches. A function can be short and still hard to follow when it has many nested branches. Pylint checks this apart from length, with max-branches at 12 by default.9 See Cyclomatic complexity.

References

  1. Martin Fowler, Function Length, bliki, 30 November 2016, the whole article and notes 3 and 4
  2. Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 3, Bad Smells in Code, Long Method
  3. Martin Fowler, with Kent Beck, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 3, Bad Smells in Code, Long Function
  4. Martin Fowler, Changes for the 2nd Edition of Refactoring, Fate of the refactorings in the first edition, Extract Method and Replace Method with Method Object
  5. Martin Fowler, Catalog of Refactorings, the cards Extract Function, Replace Temp with Query, Decompose Conditional, Split Loop and Replace Function with Command
  6. ESLint documentation, Rules, max-lines-per-function, Options, max (default 50)
  7. ESLint documentation, Rules, max-statements, Options, max (default 10)
  8. Checkstyle documentation, MethodLength, Properties, max (default 150) and countEmpty (default true)
  9. Pylint documentation, All configuration options, Design checker, --max-statements (default 50) and --max-branches (default 12)
  10. golangci-lint documentation, Linters configuration, funlen, lines (default 60) and statements (default 40)

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/CR987H/text.yaml