Replace magic numbers with named constants
✓Works with OpenClaudeYou are a refactoring specialist. The user wants to identify magic numbers in code and replace them with descriptive named constants.
What to check first
- Search your codebase for numeric literals used in calculations, comparisons, or array indexing with
grep -n "[0-9]\+" *.jsor equivalent - Identify which numbers appear multiple times or lack obvious meaning (e.g.,
if (age > 18)is clear, butmultiplier = 1.618is not)
Steps
- Scan the file for numeric literals that aren't immediately self-explanatory (timestamps, thresholds, multipliers, array indices)
- Group magic numbers by semantic meaning — e.g., all timeout values together, all permission levels together
- Create a constants object or file at the top of your module with descriptive UPPER_SNAKE_CASE names
- Replace each magic number with its corresponding constant name
- For repeated numbers with different meanings, create separate constants (don't reuse the same constant for different purposes)
- If constants are shared across multiple files, move them to a dedicated
constants.jsorconfig.jsfile - Add a comment explaining the constant's purpose if the name alone isn't sufficient
- Run your test suite to verify behavior hasn't changed
Code
// BEFORE: Magic numbers scattered throughout
function validateUser(user) {
if (user.age < 18) return false;
if (user.attempts > 5) lockAccount(user);
if (user.accountBalance < 100) notifyLow();
const multiplier = 1.618;
const timeout = 30000;
const maxRetries = 3;
return true;
}
function calculateDiscount(amount) {
if (amount > 500) return amount * 0.15;
if (amount > 250) return amount * 0.10;
return amount * 0.05;
}
// AFTER: Named constants with clear intent
const USER_CONSTANTS = {
MIN_LEGAL_AGE: 18,
MAX_LOGIN_ATTEMPTS: 5,
MINIMUM_BALANCE_THRESHOLD: 100,
GOLDEN_RATIO: 1.618,
API_TIMEOUT_MS: 30000,
MAX_RETRY_COUNT: 3,
};
const DISCOUNT_THRESHOLDS = {
PREMIUM_TIER: 500,
PREMIUM_DISCOUNT: 0.15,
STANDARD_TIER: 250,
STANDARD_DISCOUNT: 0.10,
BASE_DISCOUNT: 0.05,
};
function validateUser(user) {
if (user.age < USER_CONSTANTS.MIN_LEGAL_AGE) return false;
if (user.attempts > USER_CONSTANTS.MAX_LOGIN_ATTEMPTS) lockAccount(user);
if (user.accountBalance < USER_CONSTANTS.
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Refactoring Skills
Other Claude Code skills in the same category — free to download.
Extract Function
Extract code blocks into well-named functions
Rename Symbol
Safely rename variables, functions, classes across codebase
Remove Dead Code
Find and remove unused code
Simplify Conditionals
Simplify complex if/else chains and nested conditions
Extract Component
Extract UI code into reusable components
DRY Refactor
Find code duplication and extract shared logic
Promise to Async
Convert Promise chains to async/await
Class to Functions
Convert class-based code to functional style
Want a Refactoring skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.