Skip to content

Magic String

Easy — everyone uses thisGeneral Dev

ELI5 — The Vibe Check

A magic string is a hardcoded string value buried in code with no explanation — like finding a mysterious note that says 'ADMIN_OVERRIDE_7742' deep in the auth logic. What does it mean? Who put it there? What happens if you change it? Nobody knows. Magic strings are magic numbers' equally evil twin. Use constants, enums, or config instead.

Real Talk

A magic string is an unnamed string literal used directly in code, making the code harder to understand, maintain, and refactor. Like magic numbers, they obscure intent and create duplication risks. The fix is extracting them into named constants, enums, or configuration. Common examples include status values ('active', 'pending'), role names, and error messages.

Show Me The Code

// Bad: magic strings everywhere
if (user.role === 'super_admin_v2') {
  if (order.status === 'pending_review_3') {
    sendEmail('order-confirmation-template-b')
  }
}

// Good: named constants
const ROLES = { SUPER_ADMIN: 'super_admin_v2' } as const
const ORDER_STATUS = { PENDING_REVIEW: 'pending_review_3' } as const

if (user.role === ROLES.SUPER_ADMIN) {
  if (order.status === ORDER_STATUS.PENDING_REVIEW) {
    sendEmail(EMAIL_TEMPLATES.ORDER_CONFIRMATION)
  }
}

When You'll Hear This

"What does 'XJ-7' mean in line 47? — It's a magic string, nobody knows." / "Replace all magic strings with an enum before this gets worse."

Made with passive-aggressive love by manoga.digital. Powered by Claude.