Techniquecore
Split variable
Also called split temp, split temporary variable, remove assignments to parameters.
When one variable is assigned more than once to hold different things, give each thing its own variable, and make each one a constant where the language allows it.
- Family
- refactoring
- Intent
- Give each variable one job and one name.
- Also called
- Split Temporary Variable, Remove Assignments to Parameters
Purpose
A variable should hold one thing. When the same variable holds a perimeter and then an area, or the raw input and then the cleaned input, its name fits at most one of them, and a reader must track which one it holds at each line.
Split variable gives each of those things its own variable. The catalogue card turns a temp that holds first a perimeter and then an area into two constants, perimeter and area.1 The first edition had two refactorings for this, Split Temporary Variable and the case of a parameter that the function assigns to, Remove Assignments to Parameters; the catalogue lists both as aliases.12
The book makes one exception: a collecting variable, such as a sum or a string that a loop builds, is assigned many times on purpose and holds one thing all along. Do not split it.3
Steps
- At the declaration and the first assignment, change the name of the variable to one that says what it holds.3
- If you can, declare it as a constant:
constin JavaScript,finalin Java. - Change all the references up to the second assignment to use the changed name.
- At the second assignment, declare a variable with its own name.
- Test.
- Repeat for each later assignment.
Example
A function cleans a user name. It assigns to its parameter twice, and then reuses one result for two different values. After the split, each value has a name and is a constant.
import assert from "node:assert/strict";
function handleBefore(input) {
input = input.trim(); // the parameter now holds the trimmed text
input = input.toLowerCase(); // and now the lowercase text
let result = input.replace(/\s+/g, "-");
result = result.length > 12 ? result.slice(0, 12) : result;
return result;
}
function handle(rawInput) {
const trimmed = rawInput.trim();
const lower = trimmed.toLowerCase();
const slug = lower.replace(/\s+/g, "-");
const clipped = slug.length > 12 ? slug.slice(0, 12) : slug;
return clipped;
}
for (const s of [" Ana Pires ", "Very Long Display Name", "x"]) assert.equal(handle(s), handleBefore(s));
assert.equal(handle(" Ana Pires "), "ana-pires");
console.log("split variable: tests pass");
split variable: tests pass
With one name for each value, each line can now be read on its own, and any of the steps can be extracted or inlined. A reader no longer has to ask which input a line sees.
| Language | What the example shows |
|---|---|
| JavaScript | a reassigned parameter and a reused result split into constants, as above |
| Python | the same split; Python has no const, so the split rests on the names, and a Final annotation for a type checker |
| Go | the same split with :=, where each value gets its own name |
import re
from typing import Final
def handle_before(text: str) -> str:
text = text.strip()
text = text.lower()
result = re.sub(r"\s+", "-", text)
result = result[:12]
return result
def handle(raw_text: str) -> str:
trimmed: Final = raw_text.strip()
lower: Final = trimmed.lower()
slug: Final = re.sub(r"\s+", "-", lower)
clipped: Final = slug[:12] # a type checker reports a second assignment to a Final name
return clipped
for s in [" Ana Pires ", "Very Long Display Name", "x"]:
assert handle(s) == handle_before(s)
assert handle(" Ana Pires ") == "ana-pires"
print("split variable: tests pass")
split variable: tests pass
package main
import (
"fmt"
"strings"
)
func handle(rawInput string) string {
trimmed := strings.TrimSpace(rawInput)
lower := strings.ToLower(trimmed)
slug := strings.Join(strings.Fields(lower), "-")
clipped := clip(slug, 12)
return clipped
}
// clip returns at most the first n bytes of s.
func clip(s string, n int) string {
if len(s) > n {
return s[:n]
}
return s
}
func main() {
if got := handle(" Ana Pires "); got != "ana-pires" {
panic(got)
}
if got := handle("Very Long Display Name"); got != "very-long-di" {
panic(got)
}
fmt.Println("split variable: tests pass")
}
split variable: tests pass
When to use
- A variable assigned twice for different things. That is the case the refactoring is for.3
- A parameter that the function assigns to. Callers and readers expect a parameter to hold what was passed in.2
- Before Extract Function or Replace Temp with Query. A variable with one job is easier to replace with a query. See Replace Temp with Query.
Pitfalls
Collecting variables. A running total or a loop counter is assigned many times and holds one thing. Leave it.3
Pass by reference. In a language where a parameter can be a reference to the caller's variable, assigning to it changes the caller's value. Then the assignment is part of the function's behavior, and splitting it changes what the function does.
Long functions. Many variables with one job each can make a long function longer. That is a sign to extract functions, not a reason to keep the reuse.
Tools that do it
This refactoring is a sequence of steps, not one action of a tool. Linter rules can point at the places to start. ESLint's no-param-reassign rule "aims to prevent unintended behavior caused by modification or reassignment of function parameters".4 Its prefer-const rule "is aimed at flagging variables that are declared using the let keyword, but never reassigned after the initial assignment", which finds the variables that step 2 can make constants.5
References
- Martin Fowler, Catalog of Refactorings, Split Variable, the entry; aliases Remove Assignments to Parameters, Split Temp
- Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 6, Composing Methods, Split Temporary Variable and Remove Assignments to Parameters
- ESLint, no-param-reassign, Rule Details
- ESLint, prefer-const, Rule Details
- Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 9, Organizing Data, Split Variable, motivation, mechanics and the example of assigning to an input parameter
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 9G8Q6V Edit this page History Report an error Markdown