Programming Search⌘K

Patterncore

Divergent Change

Also called more than one reason to change.

A code smell: one module is changed for several unrelated reasons, so each change must work around code that belongs to a different concern.

Family
code-smell
Intent
Find the modules that change for more than one reason, and split them so that each part changes for one reason.

Intent

Find the modules that are changed for more than one reason, and split them so that each part has one reason to change. Then a change to one concern does not touch, and cannot break, the code of another.

Problem

A module that is changed often is not a problem in itself. The smell is a module that is changed for reasons that have nothing to do with each other. Refactoring describes the thought that signals it: a programmer sees that one set of functions in a module must change each time a database changes, and a different set must change each time a financial product is added.1

The forces are these:

  • Code grows where it is first written. A report function starts with the totals and the format in one place, because both are small. Later the business asks for a new total, and a different team asks for a new format. Each change goes into the same function.
  • Two concerns in one module share local variables, helper functions and tests. A change to one concern must be made with care not to break the other, and its tests must set up data for both.
  • Robert C. Martin states the matching design rule as "A class should have only one reason to change". He later clarified it as "Gather together the things that change for the same reasons. Separate those things that change for different reasons."2 Wikipedia lists the principle as the "S" in SOLID.2
  • The Wikipedia article gives an example that fits the smell: a module that compiles and prints a report can change because the content changes or because the format changes, and "It would be a bad design to couple two things that change for different reasons at different times."2

Solution

Split the module along the line between the concerns. Refactoring gives the steps by the shape of the code.1 The catalogue at refactoring.com has a card for each refactoring.3

  1. The two concerns run one after the other, such as reading data and then processing it: Split Phase. The first phase produces a data structure, and the second phase uses it. Each phase can then live in its own module.
  2. The two concerns are mixed in many functions: Move Function to put the functions of each concern in their own module.
  3. One function does work for both concerns: Extract Function to split it, then move the parts.
  4. The module is a class: Extract Class to move one concern and its fields into a class of its own.

A good test for the line is the list of reasons to change. Write down the last few changes to the module. If they fall into two groups that never touch the same code, the groups are the two modules.

Example

The report function adds up sales by region and formats the result as text or CSV. A change to the business rule, such as a total per month, and a change to the output, such as an HTML format, both edit this one function. The format checks are spread through the computation.

import assert from "node:assert/strict";

// Before: the computation and the format are mixed.
function reportBefore(sales, format) {
  let total = 0;
  const byRegion = new Map();
  let out = format === "csv" ? "region,amount\n" : "";
  for (const s of sales) {
    total += s.amount;
    byRegion.set(s.region, (byRegion.get(s.region) ?? 0) + s.amount);
  }
  for (const [region, amount] of byRegion) {
    out += format === "csv" ? `${region},${amount}\n` : `${region}: ${amount}\n`;
  }
  out += format === "csv" ? `total,${total}\n` : `Total: ${total}\n`;
  return out;
}

// After: phase 1 computes a summary, phase 2 renders it.
function summarize(sales) {
  const byRegion = new Map();
  for (const s of sales) byRegion.set(s.region, (byRegion.get(s.region) ?? 0) + s.amount);
  const total = [...byRegion.values()].reduce((a, b) => a + b, 0);
  return { byRegion, total };
}

const renderers = {
  text: (sum) =>
    [...sum.byRegion].map(([r, a]) => `${r}: ${a}\n`).join("") + `Total: ${sum.total}\n`,
  csv: (sum) =>
    "region,amount\n" + [...sum.byRegion].map(([r, a]) => `${r},${a}\n`).join("") + `total,${sum.total}\n`,
};

const report = (sales, format) => renderers[format](summarize(sales));

const sales = [
  { region: "north", amount: 100 },
  { region: "south", amount: 50 },
  { region: "north", amount: 25 },
];
for (const format of ["text", "csv"]) {
  assert.equal(report(sales, format), reportBefore(sales, format));
}
assert.equal(report(sales, "text"), "north: 125\nsouth: 50\nTotal: 175\n");
assert.equal(summarize(sales).total, 175);
console.log("report: tests pass");
Output
report: tests pass

After the split, a new total changes summarize and its tests, and no renderer. A new format adds one entry to renderers, and does not touch the computation. The test of summarize checks the numbers without parsing text.

Language What the example shows
JavaScript the split phase above, with a table of renderers
Python the same split, with a dataclass for the summary and a dict of renderers
Java a record for the summary, and an interface for the renderers
Go a struct for the summary, and a map from format name to render function
PythonGitHub
from dataclasses import dataclass


# Before: the computation and the format are mixed.
def report_before(sales, fmt):
    total = 0
    by_region = {}
    out = "region,amount\n" if fmt == "csv" else ""
    for s in sales:
        total += s["amount"]
        by_region[s["region"]] = by_region.get(s["region"], 0) + s["amount"]
    for region, amount in by_region.items():
        out += f"{region},{amount}\n" if fmt == "csv" else f"{region}: {amount}\n"
    out += f"total,{total}\n" if fmt == "csv" else f"Total: {total}\n"
    return out


# After: phase 1 computes a summary, phase 2 renders it.
@dataclass(frozen=True)
class Summary:
    by_region: dict
    total: int


def summarize(sales):
    by_region = {}
    for s in sales:
        by_region[s["region"]] = by_region.get(s["region"], 0) + s["amount"]
    return Summary(by_region, sum(by_region.values()))


def render_text(summary):
    lines = [f"{r}: {a}\n" for r, a in summary.by_region.items()]
    return "".join(lines) + f"Total: {summary.total}\n"


def render_csv(summary):
    lines = [f"{r},{a}\n" for r, a in summary.by_region.items()]
    return "region,amount\n" + "".join(lines) + f"total,{summary.total}\n"


RENDERERS = {"text": render_text, "csv": render_csv}


def report(sales, fmt):
    return RENDERERS[fmt](summarize(sales))


sales = [
    {"region": "north", "amount": 100},
    {"region": "south", "amount": 50},
    {"region": "north", "amount": 25},
]
for fmt in ("text", "csv"):
    assert report(sales, fmt) == report_before(sales, fmt)
assert report(sales, "text") == "north: 125\nsouth: 50\nTotal: 175\n"
assert summarize(sales).total == 175
print("report: tests pass")
Output
report: tests pass
  • A Python dict keeps the order of insertion, so the regions come out in the order they first appear in the sales, in both versions.
  • The dataclass is frozen, so a renderer cannot change the summary that another renderer also reads.
  • A new format is one function and one entry in RENDERERS. The computation and its tests do not change.
JavaGitHub
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class Main {
    record Sale(String region, int amount) {}

    // Before: the computation and the format are mixed.
    static String reportBefore(List<Sale> sales, String format) {
        boolean csv = format.equals("csv");
        int total = 0;
        Map<String, Integer> byRegion = new LinkedHashMap<>();
        StringBuilder out = new StringBuilder(csv ? "region,amount\n" : "");
        for (Sale s : sales) {
            total += s.amount();
            byRegion.merge(s.region(), s.amount(), Integer::sum);
        }
        byRegion.forEach((r, a) -> out.append(csv ? r + "," + a + "\n" : r + ": " + a + "\n"));
        out.append(csv ? "total," + total + "\n" : "Total: " + total + "\n");
        return out.toString();
    }

    // After: phase 1 computes a summary, phase 2 renders it.
    record Summary(Map<String, Integer> byRegion, int total) {}

    static Summary summarize(List<Sale> sales) {
        Map<String, Integer> byRegion = new LinkedHashMap<>();
        for (Sale s : sales) byRegion.merge(s.region(), s.amount(), Integer::sum);
        int total = byRegion.values().stream().mapToInt(Integer::intValue).sum();
        return new Summary(byRegion, total);
    }

    interface Renderer { String render(Summary s); }

    static final Map<String, Renderer> RENDERERS = Map.of(
        "text", s -> {
            StringBuilder b = new StringBuilder();
            s.byRegion().forEach((r, a) -> b.append(r).append(": ").append(a).append("\n"));
            return b.append("Total: ").append(s.total()).append("\n").toString();
        },
        "csv", s -> {
            StringBuilder b = new StringBuilder("region,amount\n");
            s.byRegion().forEach((r, a) -> b.append(r).append(",").append(a).append("\n"));
            return b.append("total,").append(s.total()).append("\n").toString();
        });

    static String report(List<Sale> sales, String format) {
        return RENDERERS.get(format).render(summarize(sales));
    }

    public static void main(String[] args) {
        List<Sale> sales = List.of(new Sale("north", 100), new Sale("south", 50), new Sale("north", 25));
        for (String f : List.of("text", "csv")) {
            if (!report(sales, f).equals(reportBefore(sales, f))) throw new AssertionError(f);
        }
        if (!report(sales, "text").equals("north: 125\nsouth: 50\nTotal: 175\n")) throw new AssertionError("text");
        if (summarize(sales).total() != 175) throw new AssertionError("total");
        System.out.println("report: tests pass");
    }
}
Output
report: tests pass
  • LinkedHashMap keeps the order of insertion. A HashMap would give the regions in an order that the tests could not rely on.
  • Map.merge with Integer::sum adds the amount to the value for the region, or stores it if the region is not there yet.
  • The Renderer interface is the contract of phase 2. A class in another package can add a format without access to the code of phase 1.
package main

import (
	"fmt"
	"strings"
)

type sale struct {
	region string
	amount int
}

// Before: the computation and the format are mixed.
func reportBefore(sales []sale, format string) string {
	csv := format == "csv"
	total := 0
	byRegion := map[string]int{}
	var order []string
	var out strings.Builder
	if csv {
		out.WriteString("region,amount\n")
	}
	for _, s := range sales {
		total += s.amount
		if _, ok := byRegion[s.region]; !ok {
			order = append(order, s.region)
		}
		byRegion[s.region] += s.amount
	}
	for _, r := range order {
		if csv {
			fmt.Fprintf(&out, "%s,%d\n", r, byRegion[r])
		} else {
			fmt.Fprintf(&out, "%s: %d\n", r, byRegion[r])
		}
	}
	if csv {
		fmt.Fprintf(&out, "total,%d\n", total)
	} else {
		fmt.Fprintf(&out, "Total: %d\n", total)
	}
	return out.String()
}

// After: phase 1 computes a summary, phase 2 renders it.
type regionTotal struct {
	region string
	amount int
}

type summary struct {
	byRegion []regionTotal
	total    int
}

func summarize(sales []sale) summary {
	index := map[string]int{}
	var s summary
	for _, x := range sales {
		i, ok := index[x.region]
		if !ok {
			i = len(s.byRegion)
			index[x.region] = i
			s.byRegion = append(s.byRegion, regionTotal{x.region, 0})
		}
		s.byRegion[i].amount += x.amount
		s.total += x.amount
	}
	return s
}

var renderers = map[string]func(summary) string{
	"text": func(s summary) string {
		var b strings.Builder
		for _, r := range s.byRegion {
			fmt.Fprintf(&b, "%s: %d\n", r.region, r.amount)
		}
		fmt.Fprintf(&b, "Total: %d\n", s.total)
		return b.String()
	},
	"csv": func(s summary) string {
		var b strings.Builder
		b.WriteString("region,amount\n")
		for _, r := range s.byRegion {
			fmt.Fprintf(&b, "%s,%d\n", r.region, r.amount)
		}
		fmt.Fprintf(&b, "total,%d\n", s.total)
		return b.String()
	},
}

func report(sales []sale, format string) string { return renderers[format](summarize(sales)) }

func main() {
	sales := []sale{{"north", 100}, {"south", 50}, {"north", 25}}
	for _, f := range []string{"text", "csv"} {
		if report(sales, f) != reportBefore(sales, f) {
			panic(f)
		}
	}
	if report(sales, "text") != "north: 125\nsouth: 50\nTotal: 175\n" || summarize(sales).total != 175 {
		panic("after")
	}
	fmt.Println("report: tests pass")
}
Output
report: tests pass
  • A Go map has no defined order of iteration, so both versions keep the regions in a slice in the order they first appear. The summary stores that order, and the renderers do not need to know about it.
  • The if csv checks in the "before" version appear three times. Each new format would add a branch to each of them.
  • The renderers are plain functions in a map. A new format needs no new type.

Consequences

Each part becomes smaller and has tests of its own. Two people can change the two parts at the same time without a merge conflict. The intermediate data structure, the summary in the example, documents the contract between the parts.

The cost is one more type and one more module. When a module has two concerns that always change together, a split adds indirection for no gain. The smell is the reasons for change, not the count of concerns in the code.

The split must follow the real reasons. A split by layer, such as all the database code in one module and all the business code in another, helps when the database and the business rules change for different reasons. If each business change also needs a database change, the layer split turns the problem into Shotgun Surgery.

How to fix it

  • Two concerns in sequence: Split Phase, with a data structure between the phases.1
  • Two concerns spread over many functions: Move Function for each function, to a module for its concern.1
  • One function with parts of both: Extract Function, then move the parts.1
  • A class with two concerns: Extract Class.1

Shotgun Surgery. The opposite smell: one change needs edits in many modules. Refactoring contrasts the two: in Divergent Change one module suffers many kinds of change, and in Shotgun Surgery one kind of change touches many modules.1 The first edition makes the same contrast.4 See Shotgun Surgery.

Large Class. A class with many concerns is often both large and divergent. See Large Class.

Single-responsibility principle. The design rule that this smell breaks. See Single-responsibility principle.

Separation of concerns. The general idea behind the split. See Separation of concerns.

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, Divergent Change and Shotgun Surgery
  2. Wikipedia, Single-responsibility principle, revision 1382198334, the introduction, History and Example
  3. Martin Fowler, Catalog of Refactorings, the cards Split Phase, Move Function, Extract Function and Extract Class
  4. Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 3, Bad Smells in Code, Divergent Change

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