Course contentsShow
← Computer Science
Lesson 2314 of 2,87252. Clean Code and RefactoringFree lesson

Avoiding Magic Numbers and String Literals

Replace unexplained literals with named constants that communicate meaning and enable easy maintenance.

Avoiding Magic Numbers and String Literals

You'll learn why unexplained literal values hurt code maintainability and how named constants fix that problem.

The Problem with "Magic" Values

A magic number or string literal is a raw value that appears directly in your code without explanation. When you write if (status == 3) or timeout = 1000, future readers (including yourself) must guess what "3" or "1000" actually represents. This creates confusion and makes changes risky—if you need to update that value, you must hunt through the entire codebase hoping you don't miss an occurrence.

Think of it like a recipe that says "add ingredient X"—without knowing what X is, you can't cook the dish or make substitutions safely.

The Solution: Named Constants

Replace mysterious literals with descriptively named constants:

const int STATUS_APPROVED = 3;
const int TIMEOUT_MILLISECONDS = 1000;
const string ERROR_MESSAGE = "Invalid input format";

if (status == STATUS_APPROVED) { ... }
timeout = TIMEOUT_MILLISECONDS;

Now the code is self-documenting. STATUS_APPROVED tells you what the value means, not just what it is. If you need to change the approval status value or message text, you change it in exactly one place—the constant declaration.

When to Extract

Extract a literal when:

  • The same value appears multiple times
  • The value's meaning isn't immediately obvious
  • The value might need to change in the future
  • It represents a domain concept (business rule, configuration)

Simple, self-explanatory values like 0, 1, or empty strings in obvious contexts can stay inline.

Key Takeaway: Named constants replace cryptic literal values with meaningful identifiers, making code self-documenting and dramatically easier to maintain and modify.