Programming Search⌘K

Patterncore

Shotgun Surgery

A code smell: one change to the behaviour of a program needs many small edits in many modules, and an edit that is missed is a bug.

Family
code-smell
Intent
Find the knowledge that is spread over many modules, and gather it in one place, so that one change is one edit.

Intent

Find the pieces of one decision that are spread over many modules, and gather them in one place. Then a change to the decision is one edit in one module, and no part of it can be missed.

Problem

A programmer gets a small request: add a discount code. The work turns out to need an edit in the price module, an edit in the receipt module and an edit in the validation module. Each edit is small. The risk is the edit that nobody remembers. Refactoring gives this as the problem: when the changes are all over the code, they are hard to find, and it is easy to miss one that matters.1

The forces are these:

  • Code is often split by technical layer: parsing, validation, storage, display. A business change, such as a new field or a new rule, cuts across all the layers, so it needs an edit in each.
  • Copy and paste spreads the same knowledge. The Wikipedia article on the smell says that the code in each place "looks similar and may only have slight variations", and that a bug in it "will be replicated many-fold".2
  • The places do not point to each other. Nothing in the price module says that the receipt module also knows the list of codes. The only guide is a search, or the memory of the person who wrote the code.

Wikipedia also notes that "There is also some evidence that this anti-pattern is correlated with higher defect rates."2

Solution

Gather the parts of the decision into one module. Refactoring names the refactorings for it.1 The catalogue at refactoring.com has a card for each.3

  1. Functions and fields in the wrong modules: Move Function and Move Field to put them in the module that owns the decision.
  2. Several functions that work on the same data: Combine Functions into Class, or Combine Functions into Transform when the functions compute values from a record that does not change.
  3. Code that does the same steps in many places: Split Phase, when the steps form a sequence that one module can own.
  4. Logic split into pieces that are too small: Inline Function and Inline Class to pull the pieces together first. Refactoring notes that the result can be a large function or class for a time, and that it can be split again in a better place.1

The goal is the second half of the rule that Robert C. Martin wrote for the single-responsibility principle: "Gather together the things that change for the same reasons."4

Example

The list of discount codes is known in three places: the price function, the receipt text and the validation. A new code needs three edits, and the test shows what happens when one is missed.

import assert from "node:assert/strict";

// Before: three functions each know the codes.
function priceBefore(cents, code) {
  if (code === "SPRING10") return Math.round(cents * 0.9);
  if (code === "VIP25") return Math.round(cents * 0.75);
  return cents;
}
function receiptBefore(code) {
  if (code === "SPRING10") return "SPRING10 (10% off)";
  if (code === "VIP25") return "VIP25 (25% off)";
  return "no discount";
}
const isValidBefore = (code) => ["SPRING10", "VIP25", "SUMMER20"].includes(code);
// SUMMER20 was added to the validation, but not to the price or the receipt.

assert.equal(isValidBefore("SUMMER20"), true);
assert.equal(priceBefore(1000, "SUMMER20"), 1000); // a valid code with no effect
console.log("before: one of three edits was made");

// After: one table owns the codes, and the three functions read it.
const discounts = new Map([["SPRING10", 10], ["VIP25", 25], ["SUMMER20", 20]]);

const isValid = (code) => discounts.has(code);
const price = (cents, code) => Math.round((cents * (100 - (discounts.get(code) ?? 0))) / 100);
const receipt = (code) => (isValid(code) ? `${code} (${discounts.get(code)}% off)` : "no discount");

assert.equal(price(1000, "SPRING10"), 900);
assert.equal(price(1000, "SUMMER20"), 800);
assert.equal(receipt("SUMMER20"), "SUMMER20 (20% off)");
assert.equal(price(1000, "BOGUS"), 1000);
assert.equal(receipt("BOGUS"), "no discount");
console.log("after: tests pass");
Output
before: one of three edits was made
after: tests pass

In the "after" version, a new code is one line in the table. The price, the receipt and the validation cannot disagree, because they read the same data. The percentage is stored once, so the receipt text cannot say 20% while the price takes 25%.

Language What the example shows
JavaScript the table of codes above, as a Map
Python the same table as a dict, in one module with the three functions
Java an enum that holds the codes and their percentages
Go a map in one package, with the three functions next to it
PythonGitHub
# Before: three functions each know the codes.
def price_before(cents, code):
    if code == "SPRING10":
        return round(cents * 0.9)
    if code == "VIP25":
        return round(cents * 0.75)
    return cents


def receipt_before(code):
    if code == "SPRING10":
        return "SPRING10 (10% off)"
    if code == "VIP25":
        return "VIP25 (25% off)"
    return "no discount"


def is_valid_before(code):
    return code in ("SPRING10", "VIP25", "SUMMER20")
# SUMMER20 was added to the validation, but not to the price or the receipt.


assert is_valid_before("SUMMER20")
assert price_before(1000, "SUMMER20") == 1000  # a valid code with no effect
print("before: one of three edits was made")

# After: one table owns the codes, and the three functions read it.
DISCOUNTS = {"SPRING10": 10, "VIP25": 25, "SUMMER20": 20}


def is_valid(code):
    return code in DISCOUNTS


def price(cents, code):
    return round(cents * (100 - DISCOUNTS.get(code, 0)) / 100)


def receipt(code):
    return f"{code} ({DISCOUNTS[code]}% off)" if is_valid(code) else "no discount"


assert price(1000, "SPRING10") == 900
assert price(1000, "SUMMER20") == 800
assert receipt("SUMMER20") == "SUMMER20 (20% off)"
assert price(1000, "BOGUS") == 1000
assert receipt("BOGUS") == "no discount"
print("after: tests pass")
Output
before: one of three edits was made
after: tests pass
  • DISCOUNTS.get(code, 0) gives 0 for an unknown code, so the price function needs no separate branch for it.
  • In a real program the three functions would be in three modules that import DISCOUNTS from one place. The import is then the visible link that the "before" version did not have.
JavaGitHub
import java.util.Optional;
import java.util.Set;

public class Main {
    // Before: three methods each know the codes.
    static long priceBefore(long cents, String code) {
        if (code.equals("SPRING10")) return Math.round(cents * 0.9);
        if (code.equals("VIP25")) return Math.round(cents * 0.75);
        return cents;
    }

    static String receiptBefore(String code) {
        if (code.equals("SPRING10")) return "SPRING10 (10% off)";
        if (code.equals("VIP25")) return "VIP25 (25% off)";
        return "no discount";
    }

    static boolean isValidBefore(String code) {
        return Set.of("SPRING10", "VIP25", "SUMMER20").contains(code);
    }
    // SUMMER20 was added to the validation, but not to the price or the receipt.

    // After: one enum owns the codes and their percentages.
    enum Discount {
        SPRING10(10), VIP25(25), SUMMER20(20);

        final int percent;

        Discount(int percent) { this.percent = percent; }

        static Optional<Discount> of(String code) {
            for (Discount d : values()) if (d.name().equals(code)) return Optional.of(d);
            return Optional.empty();
        }
    }

    static boolean isValid(String code) { return Discount.of(code).isPresent(); }

    static long price(long cents, String code) {
        int off = Discount.of(code).map(d -> d.percent).orElse(0);
        return Math.round(cents * (100 - off) / 100.0);
    }

    static String receipt(String code) {
        return Discount.of(code).map(d -> d.name() + " (" + d.percent + "% off)").orElse("no discount");
    }

    static void check(boolean ok, String what) {
        if (!ok) throw new AssertionError(what);
    }

    public static void main(String[] args) {
        check(isValidBefore("SUMMER20") && priceBefore(1000, "SUMMER20") == 1000, "before");
        System.out.println("before: one of three edits was made");

        check(price(1000, "SPRING10") == 900 && price(1000, "SUMMER20") == 800, "price");
        check(receipt("SUMMER20").equals("SUMMER20 (20% off)"), "receipt");
        check(price(1000, "BOGUS") == 1000 && receipt("BOGUS").equals("no discount"), "unknown");
        System.out.println("after: tests pass");
    }
}
Output
before: one of three edits was made
after: tests pass
  • An enum makes the list of codes a type. A switch on Discount in another class can be checked by the compiler for missing cases, which a list of strings cannot.
  • Discount.of loops over values() in place of Discount.valueOf, because valueOf throws IllegalArgumentException for an unknown name.
  • The percentage is a field of each constant, so the receipt and the price read the same number.
package main

import (
	"fmt"
	"math"
	"slices"
)

// Before: three functions each know the codes.
func priceBefore(cents int, code string) int {
	switch code {
	case "SPRING10":
		return int(math.Round(float64(cents) * 0.9))
	case "VIP25":
		return int(math.Round(float64(cents) * 0.75))
	}
	return cents
}

func receiptBefore(code string) string {
	switch code {
	case "SPRING10":
		return "SPRING10 (10% off)"
	case "VIP25":
		return "VIP25 (25% off)"
	}
	return "no discount"
}

func isValidBefore(code string) bool {
	return slices.Contains([]string{"SPRING10", "VIP25", "SUMMER20"}, code)
}

// SUMMER20 was added to the validation, but not to the price or the receipt.

// After: one table owns the codes, and the three functions read it.
var discounts = map[string]int{"SPRING10": 10, "VIP25": 25, "SUMMER20": 20}

func isValid(code string) bool { _, ok := discounts[code]; return ok }

func price(cents int, code string) int {
	return int(math.Round(float64(cents*(100-discounts[code])) / 100))
}

func receipt(code string) string {
	if !isValid(code) {
		return "no discount"
	}
	return fmt.Sprintf("%s (%d%% off)", code, discounts[code])
}

func main() {
	if !isValidBefore("SUMMER20") || priceBefore(1000, "SUMMER20") != 1000 {
		panic("before")
	}
	fmt.Println("before: one of three edits was made")

	if price(1000, "SPRING10") != 900 || price(1000, "SUMMER20") != 800 ||
		receipt("SUMMER20") != "SUMMER20 (20% off)" ||
		price(1000, "BOGUS") != 1000 || receipt("BOGUS") != "no discount" {
		panic("after")
	}
	fmt.Println("after: tests pass")
}
Output
before: one of three edits was made
after: tests pass
  • A read of a missing key from a Go map returns the zero value, so discounts["BOGUS"] is 0 and the price is unchanged. isValid uses the two-value form to tell a missing code from a code of 0%.
  • %% in the format string prints one percent sign.

Consequences

The decision has one home, and one edit changes it. A reviewer sees the whole decision in one place. A test of the module covers all its uses.

The gathered module can become a new problem. If it holds the knowledge of many decisions, it changes for many reasons, which is Divergent Change. Refactoring treats the two smells as opposites: Divergent Change is one module that suffers many kinds of change, and Shotgun Surgery is one change that touches many modules. The aim is a design where each kind of change touches one module, and each module has one kind of change.15

Not every spread is a smell. A field that is added to a record must often appear in the record, in its storage and in its display. A code generator, a schema or a table that drives all three can remove the spread. A small project may accept the three edits, if the tests fail when one of them is missing.

How to fix it

Divergent Change. The opposite smell. See Divergent Change.

Duplicated Code. Copies of the same logic make each change into many edits. See Duplicated Code.

Repeated Switches. The same switch in many functions is a common cause of this smell. See Repeated Switches.

Feature Envy. A function that lives far from the data it uses is one of the pieces that a change must find. See Feature Envy.

References

  1. Martin Fowler, with Kent Beck, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 3, Bad Smells in Code, Shotgun Surgery
  2. Wikipedia, Shotgun surgery, revision 1381335030, the introduction and Consequences of shotgun surgery
  3. Martin Fowler, Catalog of Refactorings, the cards Move Function, Move Field, Combine Functions into Class, Combine Functions into Transform, Split Phase, Inline Function and Inline Class
  4. Wikipedia, Single-responsibility principle, revision 1382198334, the quote from Robert C. Martin's blog post of 2014
  5. Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 3, Bad Smells in Code, Shotgun Surgery

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