Programming Search⌘K

Patterncore

Mysterious Name

Also called unclear name, bad name.

A code smell: a function, variable, field or module has a name that does not say what it does or what it holds, so the reader must read the code behind the name to learn it.

Family
code-smell
Intent
Find the names that hide the purpose of the code, and rename them so that the name tells the reader what the code does.

Intent

Find the names that hide what the code does, and change them so that the name says it. A good name lets a reader skip the body of a function, or the history of a variable. A mysterious name forces the reader to open it.

Problem

Code is read many more times than it is written, and names are most of what a reader sees. A function call shows its name and its arguments, not its body. A variable that is used 40 lines after it is set shows only its name at the place where it is used. When the name does not say what the thing is, the reader must find out, and must keep the answer in mind.

The forces are these:

  • A name is chosen when the code is first written, often before its purpose is clear. Later the purpose changes, and the name stays.
  • A good name is hard to find. Fowler keeps on his site the saying attributed to Phil Karlton: "There are only two hard things in Computer Science: cache invalidation and naming things."1
  • Short names are right in some places. The Go code review guide prefers c to lineCount for a local variable with a small scope, and states the rule: "the further from its declaration that a name is used, the more descriptive the name must be."2 So the length of a name is not the test. The test is whether the reader at each use knows what the name means.
  • Some names are part of an interface: a public function, a field of a JSON document, a column of a table. Changing them breaks the code of other people.

Refactoring puts this smell first in its list of 24.3

Solution

The smell has two parts: a name, and the purpose of the thing behind it. The name is mysterious when the two do not match. There are three common forms:

  1. A name that says nothing: data, tmp, x, calc, process, handle, manager, info.
  2. A name that says how, not what: loopOverList, stringToInt2, checkFlags.
  3. A name that lies: getUser that also writes to the database, isValid that returns a count, total that holds the total without tax in one branch and with tax in another.

The fix is a rename. Refactoring names three refactorings for it: Change Function Declaration for a function, Rename Variable for a variable, and Rename Field for a field of a record or a class.3 In the online catalogue, Change Function Declaration has the aliases Rename Function and Rename Method, from the first edition.4

A rename changes no behaviour, so the tests that pass before it pass after it. But the work of a rename is to understand the code well enough to name it. Refactoring makes the point that when no good name comes to mind, the code often has a deeper problem in its design.3 A function that cannot be named often does two things. Then the fix is to split it, with Extract function, and to name each part.

Example

The function calc takes a list of phone calls and a number of free minutes, and returns the hours to bill. Nothing in its name or its parameters says so. The example files show it in four languages, with the same tests on the mysterious version and the renamed one.

import assert from "node:assert/strict";

function calc(l, x) {
  let n = 0;
  for (const e of l) {
    if (e.minutes > x) n += e.minutes;
  }
  return n / 60;
}

function billableHours(calls, freeMinutes) {
  let billedMinutes = 0;
  for (const call of calls) {
    if (call.minutes > freeMinutes) billedMinutes += call.minutes;
  }
  return billedMinutes / 60;
}

const calls = [{ minutes: 5 }, { minutes: 30 }, { minutes: 45 }];
for (const f of [calc, billableHours]) {
  assert.equal(f(calls, 10), 1.25);
  assert.equal(f([], 10), 0);
  console.log(`${f.name}: tests pass`);
}
Output
calc: tests pass
billableHours: tests pass

The renamed version shows a business rule that calc hid. A call longer than the free minutes is billed in full, not only for the minutes over the limit. With the names l, x and n, a reader cannot tell if that is the intent or a bug. With freeMinutes and billedMinutes, the question is clear, and a reader can ask it.

Language What the example shows
JavaScript the rename above, with node:assert
Python the same rename; PEP 8 also forbids l as a one-letter name
Java a rename of a static method and its parameters, with a record for the call
Go a rename of an unexported function; the short loop variable c stays, because its scope is two lines
PythonGitHub
def calc(l, x):
    n = 0
    for e in l:
        if e["minutes"] > x:
            n += e["minutes"]
    return n / 60


def billable_hours(calls, free_minutes):
    billed_minutes = 0
    for call in calls:
        if call["minutes"] > free_minutes:
            billed_minutes += call["minutes"]
    return billed_minutes / 60


calls = [{"minutes": 5}, {"minutes": 30}, {"minutes": 45}]
for f in (calc, billable_hours):
    assert f(calls, 10) == 1.25
    assert f([], 10) == 0
    print(f"{f.__name__}: tests pass")
Output
calc: tests pass
billable_hours: tests pass
  • The parameter l breaks a rule of PEP 8 as well as being mysterious: PEP 8 forbids l, O and I as one-letter names, because some fonts show them like 1 and 0.
  • A rename tool changes the uses of a name that it can resolve. A key such as "minutes" is a string, so a rename of the variable does not change it. A change of the key is Rename Field, and the tests must cover each place that reads it.
  • Pylint's disallowed-name check reports names from a list, by default foo, bar, baz, toto, tutu and tata. It does not report calc or l.
JavaGitHub
import java.util.List;

public class Main {
    record Call(int minutes) {}

    static double calc(List<Call> l, int x) {
        int n = 0;
        for (Call e : l) {
            if (e.minutes() > x) n += e.minutes();
        }
        return n / 60.0;
    }

    static double billableHours(List<Call> calls, int freeMinutes) {
        int billedMinutes = 0;
        for (Call call : calls) {
            if (call.minutes() > freeMinutes) billedMinutes += call.minutes();
        }
        return billedMinutes / 60.0;
    }

    static void check(String name, java.util.function.BiFunction<List<Call>, Integer, Double> f) {
        List<Call> calls = List.of(new Call(5), new Call(30), new Call(45));
        if (f.apply(calls, 10) != 1.25) throw new AssertionError(name);
        if (f.apply(List.of(), 10) != 0.0) throw new AssertionError(name);
        System.out.println(name + ": tests pass");
    }

    public static void main(String[] args) {
        check("calc", Main::calc);
        check("billableHours", Main::billableHours);
    }
}
Output
calc: tests pass
billableHours: tests pass
  • The record Call already has a good name for its component, so the rename touches only the method, its parameters and its locals. In a typed language, the compiler finds every caller, so a rename of a method is safe within one build.
  • The Rename refactoring of IntelliJ IDEA changes the declaration and every reference to it.
  • n / 60 with an int would truncate to 1. The literal 60.0 makes the division a double division. A name such as billedMinutes makes it clearer that the unit changes here, from minutes to hours.
package main

import "fmt"

type call struct{ minutes int }

func calc(l []call, x int) float64 {
	n := 0
	for _, e := range l {
		if e.minutes > x {
			n += e.minutes
		}
	}
	return float64(n) / 60
}

func billableHours(calls []call, freeMinutes int) float64 {
	billedMinutes := 0
	for _, c := range calls {
		if c.minutes > freeMinutes {
			billedMinutes += c.minutes
		}
	}
	return float64(billedMinutes) / 60
}

func main() {
	calls := []call{{5}, {30}, {45}}
	for _, f := range []struct {
		name string
		fn   func([]call, int) float64
	}{{"calc", calc}, {"billableHours", billableHours}} {
		if f.fn(calls, 10) != 1.25 || f.fn(nil, 10) != 0 {
			panic(f.name)
		}
		fmt.Println(f.name + ": tests pass")
	}
}
Output
calc: tests pass
billableHours: tests pass
  • The loop variable c stays short. Its scope is two lines, and the Go code review guide asks for short names in small scopes. The parameter freeMinutes is used further from its declaration, so it gets the longer name.
  • gopls implements the rename request of the Language Server Protocol, so any editor that uses gopls can rename a Go symbol in all the files of a module.
  • In Go, the first letter of a name decides if it is exported. A rename from billableHours to BillableHours changes the API of the package, not only the name.

Consequences

Renames are cheap when the name is local. An IDE does them across the whole project. IntelliJ IDEA's Rename refactoring changes a symbol "and all the references to them throughout code".5 Visual Studio Code has the command Rename Symbol (F2), and some languages support it across files.6 For Go, the language server gopls implements the rename request of the Language Server Protocol.7 A tool rename is safer than search and replace, because the tool knows the scopes.

Renames are expensive when the name is published. A public function has callers outside the project. A field name can be in stored data, in a JSON API or in a database column. Change Function Declaration has a migration form for this case: add the function with the good name, make the old name call it, mark the old name as deprecated, and remove it when no caller is left.3

Dynamic languages make renames harder for tools. A name that is built from a string, or a field that is read with obj[key], is not found by the rename tool. The tests must cover these uses.

How to fix it

  • A function or method: Change Function Declaration. Rename it, and use the migration form when it is published.3
  • A local variable or a parameter: Rename Variable. The scope decides the effort: a local variable needs one function changed, a module-level one needs all its readers changed.3
  • A field of a record or a class: Rename Field. Encapsulate the field first when many places use it directly.3
  • A name that does not come: split the code with Extract function, and name each part.

Linters can find some mysterious names, but not most of them. Pylint reports disallowed-name for names in its bad-names list, such as foo, bar and baz.8 The ESLint rule id-length enforces a minimum length, two characters by default.9 A rule can find x. It cannot know that total holds the wrong total. That needs a person who reads the code.

Magic numbers. A literal such as 0.19 with no name is a mysterious name of another kind: the value has no name at all. See Magic number and the refactoring Replace Magic Literal.

Comments. A comment that explains what a variable holds is often a sign that the variable needs a better name. See Comments (the smell) and Comment (the language construct).

Boolean parameter. A call such as send(msg, true) has an argument with no name at the call site. See Boolean parameter.

Primitive Obsession. A type can have a mysterious name too. A parameter of type string that holds a phone number says less than a parameter of type PhoneNumber. See Primitive Obsession.

Names to avoid. Some style guides forbid names that a reader can confuse with other characters. PEP 8 says: "Never use the characters ‘l’ (lowercase letter el), ‘O’ (uppercase letter oh), or ‘I’ (uppercase letter eye) as single character variable names."10 The reason is that some fonts show them like the digits one and zero.

References

  1. Martin Fowler, Two Hard Things, bliki, the saying attributed to Phil Karlton
  2. Go Wiki, Go Code Review Comments, Variable Names
  3. Martin Fowler, with Kent Beck, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 3, Bad Smells in Code, Mysterious Name
  4. Martin Fowler, Catalog of Refactorings, the cards Change Function Declaration (aliases Rename Function, Rename Method), Rename Variable and Rename Field
  5. IntelliJ IDEA documentation, Rename refactorings, the introduction
  6. Visual Studio Code documentation, Refactoring, Rename symbol
  7. gopls documentation, Code transformation features, Rename
  8. Pylint documentation, disallowed-name / C0104, the description and the configuration bad-names
  9. ESLint documentation, Rules, id-length, the rule summary and the default minimum of 2
  10. PEP 8, Style Guide for Python Code, Naming Conventions, Names to Avoid

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