43

Replace Magic Literal


Goal

Bare numbers and strings that encode domain concepts become named constants whose name says what the value represents.

Before the refactoring
function trip(distance) {
  return distance * 1.609;
}
After the refactoring
const KM_PER_MILE = 1.609;
function trip(distance) {
  return distance * KM_PER_MILE;
}
Savings

Searches by domain term find every callsite; changing the value is one edit; the constant invites code-side documentation when it's truly load-bearing.

Note

Naming every literal can drown the file in trivia — only name literals that carry domain meaning the surrounding code can't speak.