Script Valley
Writing Clean Code: Naming, Functions & Structure
Refactoring: Making Existing Code ReadableLesson 5.3

Replace magic values with named constants and enums

replacing magic numbers, replacing magic strings, enums in JavaScript and Python, const objects as enums, string union types

Named Constants and Enums: Eliminating Magic Values

Replacing magic values with named constants

A magic value is any literal โ€” number or string โ€” embedded in logic without a name. They're maintenance traps: when the value changes, you have to find every occurrence by searching for the literal, and you can never be sure you found them all.

// Bad โ€” three magic values
if (retries > 3) throw new Error();
if (order.status === 'pending') processOrder();
if (user.role === 'admin') showDashboard();

Replace them with named constants:

const MAX_RETRY_ATTEMPTS = 3;

const ORDER_STATUS = Object.freeze({
  PENDING: 'pending',
  APPROVED: 'approved',
  REJECTED: 'rejected'
});

const USER_ROLE = Object.freeze({
  ADMIN: 'admin',
  MEMBER: 'member',
  GUEST: 'guest'
});

// Now readable and refactor-safe
if (retries > MAX_RETRY_ATTEMPTS) throw new Error();
if (order.status === ORDER_STATUS.PENDING) processOrder();
if (user.role === USER_ROLE.ADMIN) showDashboard();

Object.freeze() in JavaScript makes the object immutable so values can't be accidentally changed. In TypeScript, use string literal union types or enums for compile-time safety. In Python, use the Enum class.

from enum import Enum

class OrderStatus(Enum):
    PENDING = 'pending'
    APPROVED = 'approved'
    REJECTED = 'rejected'

if order.status == OrderStatus.PENDING: ...

The benefit: if 'pending' ever changes to 'awaiting_payment', you change one constant definition and everything using it updates automatically.

Up next

How to remove duplicate code with the DRY principle

Sign in to track progress

Replace magic values with named constants and enums โ€” Refactoring: Making Existing Code Readable โ€” Writing Clean Code: Naming, Functions & Structure โ€” Script Valley โ€” Script Valley