Replace Magic Number with Symbolic Constant.

🚨 Problems

Your code uses a number that has a certain meaning to it.

function potentialEnergy(mass: number, height: number): number {
    return mass * height * 9.81;
}

âś… Solution

Replace this number with a constant that has a human-readable name explaining the meaning of the number.

const GRAVITATIONAL_CONSTANT = 9.81;
function potentialEnergy(mass: number, height: number): number {
    return mass * height * GRAVITATIONAL_CONSTANT;
}

🔍 Why Refactor

A magic number is a numeric value that’s encountered in the source but has no obvious meaning. This “anti-pattern” makes it harder to understand the program and refactor the code.

Yet more difficulties arise when you need to change this magic number. Find and replace won’t work for this: the same number may be used for different purposes in different places, meaning that you will have to verify every line of code that uses this number.

💪🏽 Benefits

The symbolic constant can serve as live documentation of the meaning of its value.

It’s much easier to change the value of a constant than to search for this number throughout the entire codebase, without the risk of accidentally changing the same number used elsewhere for a different purpose.

Reduce duplicate use of a number or string in the code. This is especially important when the value is complicated and long (such as 3.14159 or 0xCAFEBABE).

  • Clean Code - Page 300 - G25: Replace Magic Numbers with Named Constants