Course contentsShow
← Software Engineering
Lesson 352 of 1,93310. RefactoringFree lesson

Replace Magic Numbers with Constants

Eliminate unexplained literal values by extracting them into named constants that document their meaning and purpose.

Replace Magic Numbers with Constants

What you'll learn: How to make your code self-documenting by replacing mysterious numeric values with clearly named constants.

What Are Magic Numbers?

A "magic number" is a literal value (like 7, 3.14159, or 100) that appears directly in your code without explanation. When you or another developer reads if (status == 2), you have no idea what 2 means. Is it success? Failure? Pending? The number is "magical" because its meaning isn't obvious.

The Problem with Magic Values

Imagine reading a recipe that says "add 5 of the ingredient." Five what? Cups? Tablespoons? The number means nothing without context. The same happens in code—a bare 86400 tells you nothing, but SECONDS_PER_DAY immediately communicates intent.

Magic numbers create several problems:

  • Unclear intent: Readers must guess what the value represents
  • Error-prone changes: If that number appears in 10 places, you might miss one when updating
  • No single source of truth: The same conceptual value might be written slightly differently in different places

The Solution: Named Constants

Extract the literal into a named constant that explains its purpose:

// Before (magic number)
if (age >= 18) { ... }

// After (named constant)
const MINIMUM_VOTING_AGE = 18;
if (age >= MINIMUM_VOTING_AGE) { ... }

The constant name documents why the value exists. If the value needs to change, you update it in one place.

When to Extract

Not every number is "magic." The 0 in counter = 0 or 1 in index + 1 are often self-evident. Extract constants when the value has domain meaning or might change.

Key Takeaway: Replace unexplained literal values with descriptive named constants to make your code self-documenting, maintainable, and less error-prone.