Programming Search⌘K

Patterncore

Comments

Also called comments smell, deodorant comments.

A code smell, not the practice of writing comments: a comment explains what unclear code does, where clearer code would not need the comment.

Family
code-smell
Intent
Find the comments that explain what a block of code does, and change the code so that its names and structure say it, keeping the comments that say why.

Intent

This page is about a code smell named Comments, not about the practice of writing comments; for comments as a language feature, see Comment. The smell is a comment that is there because the code is hard to read. Find the comments that explain what a block does, and change the code so that a name or a check says it. Keep the comments that say why the code is as it is.

Problem

A comment is not bad. Refactoring says so plainly: comments are not a bad smell, and some are a sign of care.1 The smell is the use of a comment as a cover. A long function with a comment above each block, or a comment such as // x must be positive here, is a comment that does the work of a missing function name or a missing check.

Refactoring puts the advice in one line: when a comment seems needed, first try to refactor the code until the comment is not needed.1 Wikipedia describes the same view: "The need to explain the what is a sign that it is too complex and should be re-worked."2 It also notes that the question is not settled, and that "Experts have varying viewpoints on whether, and when, comments are appropriate in source code."2

The forces are these:

  • A comment is the quickest way to explain a block of code. It costs one line and no change to the code.
  • The compiler does not read the comment. When the code changes, the comment can stay as it was and become false, and no test fails.
  • A comment above a block in a long function marks a function that is waiting to be extracted. The comment is already its name.
  • A comment that states a condition, such as // the list is sorted here, is an assertion that nothing checks.
  • Some comments carry what code cannot say: why a choice was made, what was tried and failed, what the author is not sure about. Refactoring names these as the good uses.1

Solution

Refactoring names a refactoring for each kind of explaining comment.1 The catalogue at refactoring.com has a card for each, and lists Rename Function as one of the names of Change Function Declaration.3

  1. A comment that explains a block: Extract Function, and use the comment as the name of the function.
  2. A comment that explains what a function does, when the function is already extracted: Change Function Declaration, to give the function a name that says it.
  3. A comment that explains an expression: Extract Variable, and use the comment as the name of the variable.
  4. A comment that states a required condition: Introduce Assertion, so that the program checks it.

The first edition gives the same moves, and the same rule for the comments that remain: a comment is a good place to say why something is done, and to mark the parts the author is unsure of.4

Languages give the checking comment a form. The Python reference describes assert as "a convenient way to insert debugging assertions into a program", and notes that the check is removed when optimization is requested.5 An assertion is for a condition that the programmer believes is always true, not for input that a user can get wrong.

Some comments are required, and they are not the smell. Go's guide asks that "Every exported (capitalized) name should have a doc comment", and tools read those comments to build the documentation.6 A doc comment says what a function promises to its callers, which its name alone cannot.

Example

A function computes the price of a shipment. Comments mark its three steps and the condition that it assumes, and one comment says why the minimum charge exists.

import assert from "node:assert/strict";

// Before: comments explain what each block does.
function shippingCentsBefore(parcels, zone) {
  // weight must be positive for every parcel
  // compute the total weight in grams
  let grams = 0;
  for (const p of parcels) grams += p.grams;
  // round up to whole kilograms
  const kg = Math.ceil(grams / 1000);
  // look up the rate for the zone (1 = domestic, 2 = europe, other = world)
  const rate = zone === 1 ? 450 : zone === 2 ? 900 : 1600;
  // the carrier charges at least 2 kg per shipment, see contract section 4
  return Math.max(kg, 2) * rate;
}

// After: names and an assertion say what; one comment says why.
const RATE_CENTS_PER_KG = { domestic: 450, europe: 900, world: 1600 };
const zoneName = (zone) => (zone === 1 ? "domestic" : zone === 2 ? "europe" : "world");

function billableKilograms(parcels) {
  assert.ok(parcels.every((p) => p.grams > 0), "every parcel must have a positive weight");
  const grams = parcels.reduce((t, p) => t + p.grams, 0);
  const kg = Math.ceil(grams / 1000);
  // The carrier charges at least 2 kg per shipment (contract, section 4).
  return Math.max(kg, 2);
}

function shippingCents(parcels, zone) {
  return billableKilograms(parcels) * RATE_CENTS_PER_KG[zoneName(zone)];
}

const parcels = [{ grams: 700 }, { grams: 1450 }];
for (const zone of [1, 2, 3]) assert.equal(shippingCents(parcels, zone), shippingCentsBefore(parcels, zone));
assert.equal(shippingCents([{ grams: 300 }], 1), 900); // the minimum applies
assert.equal(shippingCents(parcels, 2), 2700);
assert.throws(() => shippingCents([{ grams: 0 }], 1), /positive weight/);
console.log("shipping: tests pass");
Output
shipping: tests pass

In the second version four of the five comments are gone. The comments on the total weight and on rounding up became the function billableKilograms, the zone comment became a table with names, and the comment on positive weights became an assertion that fails if it is false. The comment that stays says why the minimum exists, which no name could say.

Language What the example shows
JavaScript comments turned into a function, a table and an assertion, as above
Python the same, with assert and a docstring for the extracted function
Java the same, with an enum for the zones and an exception for the check
Go the same, with a doc comment on the exported function
PythonGitHub
import math


# Before: comments explain what each block does.
def shipping_cents_before(parcels, zone):
    # weight must be positive for every parcel
    # compute the total weight in grams
    grams = 0
    for p in parcels:
        grams += p["grams"]
    # round up to whole kilograms
    kg = math.ceil(grams / 1000)
    # look up the rate for the zone (1 = domestic, 2 = europe, other = world)
    rate = 450 if zone == 1 else 900 if zone == 2 else 1600
    # the carrier charges at least 2 kg per shipment, see contract section 4
    return max(kg, 2) * rate


# After: names and an assertion say what; one comment says why.
RATE_CENTS_PER_KG = {"domestic": 450, "europe": 900, "world": 1600}


def zone_name(zone):
    return {1: "domestic", 2: "europe"}.get(zone, "world")


def billable_kilograms(parcels):
    """Return the weight to charge for, in whole kilograms, with the carrier's minimum applied."""
    assert all(p["grams"] > 0 for p in parcels), "every parcel must have a positive weight"
    kg = math.ceil(sum(p["grams"] for p in parcels) / 1000)
    # The carrier charges at least 2 kg per shipment (contract, section 4).
    return max(kg, 2)


def shipping_cents(parcels, zone):
    return billable_kilograms(parcels) * RATE_CENTS_PER_KG[zone_name(zone)]


parcels = [{"grams": 700}, {"grams": 1450}]
for zone in [1, 2, 3]:
    assert shipping_cents(parcels, zone) == shipping_cents_before(parcels, zone)
assert shipping_cents([{"grams": 300}], 1) == 900
assert shipping_cents(parcels, 2) == 2700
if __debug__:
    try:
        shipping_cents([{"grams": 0}], 1)
        raise RuntimeError("the assertion must fail")
    except AssertionError as e:
        assert "positive weight" in str(e)
print("shipping: tests pass")
Output
shipping: tests pass
  • The docstring of billable_kilograms is a comment that tools read: help(billable_kilograms) prints it. It says what the function promises, which is not a smell.
  • assert is skipped when Python runs with -O, so the test of the failing case is inside if __debug__:. A check that must run in production should raise ValueError in place of the assertion.
JavaGitHub
import java.util.List;

public class Main {
    record Parcel(int grams) {}

    // Before: comments explain what each block does.
    static int shippingCentsBefore(List<Parcel> parcels, int zone) {
        // weight must be positive for every parcel
        // compute the total weight in grams
        int grams = 0;
        for (Parcel p : parcels) grams += p.grams();
        // round up to whole kilograms
        int kg = (grams + 999) / 1000;
        // look up the rate for the zone (1 = domestic, 2 = europe, other = world)
        int rate = zone == 1 ? 450 : zone == 2 ? 900 : 1600;
        // the carrier charges at least 2 kg per shipment, see contract section 4
        return Math.max(kg, 2) * rate;
    }

    // After: names and a check say what; one comment says why.
    enum Zone {
        DOMESTIC(450), EUROPE(900), WORLD(1600);

        final int centsPerKg;
        Zone(int centsPerKg) { this.centsPerKg = centsPerKg; }

        static Zone of(int code) { return code == 1 ? DOMESTIC : code == 2 ? EUROPE : WORLD; }
    }

    /** Returns the weight to charge for, in whole kilograms, with the carrier's minimum applied. */
    static int billableKilograms(List<Parcel> parcels) {
        if (!parcels.stream().allMatch(p -> p.grams() > 0)) {
            throw new IllegalArgumentException("every parcel must have a positive weight");
        }
        int grams = parcels.stream().mapToInt(Parcel::grams).sum();
        int kg = Math.ceilDiv(grams, 1000);
        // The carrier charges at least 2 kg per shipment (contract, section 4).
        return Math.max(kg, 2);
    }

    static int shippingCents(List<Parcel> parcels, Zone zone) {
        return billableKilograms(parcels) * zone.centsPerKg;
    }

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

    public static void main(String[] args) {
        List<Parcel> parcels = List.of(new Parcel(700), new Parcel(1450));
        for (int code : new int[] {1, 2, 3}) {
            check(shippingCents(parcels, Zone.of(code)) == shippingCentsBefore(parcels, code), "zone " + code);
        }
        check(shippingCents(List.of(new Parcel(300)), Zone.DOMESTIC) == 900, "minimum");
        check(shippingCents(parcels, Zone.EUROPE) == 2700, "europe");
        try {
            shippingCents(List.of(new Parcel(0)), Zone.DOMESTIC);
            throw new AssertionError("the check must fail");
        } catch (IllegalArgumentException expected) {
        }
        System.out.println("shipping: tests pass");
    }
}
Output
shipping: tests pass
  • The enum replaces the comment that listed the zone codes. Each zone has a name and a rate, and a caller cannot pass a zone that does not exist.
  • Java's assert statement is disabled unless the JVM runs with -ea, so this example uses an exception for the check, which always runs.
  • Math.ceilDiv (Java 18) rounds up, which replaces the (grams + 999) / 1000 idiom and the comment that explained it.
package main

import (
	"errors"
	"fmt"
)

type Parcel struct{ Grams int }

// Before: comments explain what each block does.
func shippingCentsBefore(parcels []Parcel, zone int) int {
	// weight must be positive for every parcel
	// compute the total weight in grams
	grams := 0
	for _, p := range parcels {
		grams += p.Grams
	}
	// round up to whole kilograms
	kg := (grams + 999) / 1000
	// look up the rate for the zone (1 = domestic, 2 = europe, other = world)
	rate := 1600
	if zone == 1 {
		rate = 450
	} else if zone == 2 {
		rate = 900
	}
	// the carrier charges at least 2 kg per shipment, see contract section 4
	return max(kg, 2) * rate
}

// After: names and a check say what; one comment says why.

// Zone is a shipping zone. Its value is the rate in cents per kilogram.
type Zone int

const (
	Domestic Zone = 450
	Europe   Zone = 900
	World    Zone = 1600
)

func zoneOf(code int) Zone {
	switch code {
	case 1:
		return Domestic
	case 2:
		return Europe
	}
	return World
}

var ErrWeight = errors.New("every parcel must have a positive weight")

// BillableKilograms returns the weight to charge for, in whole kilograms,
// with the carrier's minimum applied. It returns ErrWeight if a parcel has no weight.
func BillableKilograms(parcels []Parcel) (int, error) {
	grams := 0
	for _, p := range parcels {
		if p.Grams <= 0 {
			return 0, ErrWeight
		}
		grams += p.Grams
	}
	kg := (grams + 999) / 1000
	// The carrier charges at least 2 kg per shipment (contract, section 4).
	return max(kg, 2), nil
}

// ShippingCents returns the price of a shipment of parcels to a zone.
func ShippingCents(parcels []Parcel, zone Zone) (int, error) {
	kg, err := BillableKilograms(parcels)
	return kg * int(zone), err
}

func must(n int, err error) int {
	if err != nil {
		panic(err)
	}
	return n
}

func main() {
	parcels := []Parcel{{700}, {1450}}
	for _, code := range []int{1, 2, 3} {
		if must(ShippingCents(parcels, zoneOf(code))) != shippingCentsBefore(parcels, code) {
			panic(fmt.Sprint("zone ", code))
		}
	}
	if must(ShippingCents([]Parcel{{300}}, Domestic)) != 900 || must(ShippingCents(parcels, Europe)) != 2700 {
		panic("prices")
	}
	if _, err := ShippingCents([]Parcel{{0}}, Domestic); !errors.Is(err, ErrWeight) {
		panic("the check must fail")
	}
	fmt.Println("shipping: tests pass")
}
Output
shipping: tests pass
  • BillableKilograms and ShippingCents are exported, so each has a doc comment that starts with its name, as the Go guide asks. go doc prints these comments.
  • Go has no assertions. The check returns an error, and the caller decides what to do with it.

Consequences

The code says what it does in names that the compiler and the tests see. A rename changes every use, and an assertion fails when its condition is false, so the explanation cannot drift from the code the way a comment can.

The fix has limits. Some code is hard because the problem is hard, such as a numeric algorithm or a workaround for a bug in a library. A name cannot explain that, and a comment with a reference is the right tool. Removing such comments in the name of clean code takes away the information a reader needs most.

A checked condition differs from a comment in one more way: it costs time at run time, and in Python it is removed when assertions are disabled. A condition that must hold in production, such as a valid input from a user, needs a normal check that raises an error, not an assertion.

How to fix it

Comment. The language feature, and the kinds of comments that languages and tools support. See Comment.

Long Function. A comment above each block is the most common sign of a function that should be split. See Long Function.

Mysterious Name. A comment that explains a name is a sign that the name is wrong. See Mysterious Name.

Assertions. The language feature that turns a stated condition into a checked one. See Assertions.

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, Comments
  2. Wikipedia, Comment (computer programming), revision 1381653525, the introduction, Describe intent, and Need for comments
  3. Martin Fowler, Catalog of Refactorings, the cards Extract Function, Change Function Declaration (alias Rename Function), Introduce Assertion and Extract Variable
  4. Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 3, Bad Smells in Code, Comments
  5. Python Language Reference, simple statements, The assert statement
  6. Go Doc Comments, the introduction

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