Skip to content
Dev Discovers

The Dangers of Magic Numbers and Strings in Code

concepts4 min read

Magic numbers and strings are values that appear throughout code without any clear explanation of their meaning. They can be problematic because they make the code harder to understand and maintain.

Examples

Magic Numbers

Here are some code examples for magic numbers and how they can be refactored:

// Before:
for (let i = 0; i < 5; i++) {
console.log(`Iteration ${i + 1}`);
}
// After:
const MAX_ITERATIONS = 5;
for (let i = 0; i < MAX_ITERATIONS; i++) {
console.log(`Iteration ${i + 1}`);
}

// Before:
function isWeekend(day) {
return day === 6 || day === 7;
}
// After:
const WEEKEND_DAYS = [6, 7];
function isWeekend(day) {
return WEEKEND_DAYS.includes(day);
}

// Before:
function getDayName(day) {
switch (day) {
case 0:
return 'Sunday';
case 1:
return 'Monday';
case 2:
return 'Tuesday';
case 3:
return 'Wednesday';
case 4:
return 'Thursday';
case 5:
return 'Friday';
case 6:
return 'Saturday';
default:
return 'Invalid day';
}
}
// After:
const DAY_NAMES = {
0: 'Sunday',
1: 'Monday',
2: 'Tuesday',
3: 'Wednesday',
4: 'Thursday',
5: 'Friday',
6: 'Saturday'
};
function getDayName(day) {
return DAY_NAMES[day] || 'Invalid day';
}

Magic Strings

Here are some examples of refactoring code that uses magic strings:

// Before:
function validateInput(input) {
if (input.type === "email") {
// validate email input
} else if (input.type === "password") {
// validate password input
} else if (input.type === "username") {
// validate username input
} else {
throw new Error("Invalid input type: " + input.type);
}
}
// After:
const INPUT_TYPE = {
EMAIL: "email",
PASSWORD: "password",
USERNAME: "username",
};
function validateInput(input) {
if (input.type === INPUT_TYPE.EMAIL) {
// validate email input
} else if (input.type === INPUT_TYPE.PASSWORD) {
// validate password input
} else if (input.type === INPUT_TYPE.USERNAME) {
// validate username input
} else {
throw new Error("Invalid input type: " + input.type);
}
}

// Before:
function displayMessage(level, message) {
if (level === "INFO") {
console.log("INFO: " + message);
} else if (level === "WARNING") {
console.warn("WARNING: " + message);
} else if (level === "ERROR") {
console.error("ERROR: " + message);
} else {
console.log(message);
}
}
// After:
const MESSAGE_LEVEL = {
INFO: "info",
WARNING: "warning",
ERROR: "error",
};
function displayMessage(level, message) {
switch (level) {
case MESSAGE_LEVEL.INFO:
console.log("INFO: " + message);
break;
case MESSAGE_LEVEL.WARNING:
console.warn("WARNING: " + message);
break;
case MESSAGE_LEVEL.ERROR:
console.error("ERROR: " + message);
break;
default:
console.log(message);
break;
}
}

Risks of Using Magic Numbers and Strings

Using magic numbers and strings in code can be risky because it can make the code harder to understand, maintain, and debug.

For example, if a developer needs to modify the code and encounters a magic number or string, they may not know what it represents or what effect changing it will have on the program's behavior. This can lead to errors and unexpected behavior.

Avoiding magic numbers and strings in code can make the code more maintainable, extensible, and easier to understand. It can also reduce the risk of errors and unexpected behavior, as well as make the code more consistent and readable.

How to Avoid Magic Numbers and Strings

The best way to avoid magic numbers and strings in code is to use constants or enums with meaningful names like in the examples above. Here's another example of replacing magic numbers with well-named variables:

const PI = 3.14159;
const MAX_ATTEMPTS = 3;
const ERROR_CODES = {
NOT_FOUND: 404,
SERVER_ERROR: 500
};

Tools to Detect and Prevent Magic Numbers and Strings

There are several tools that can help detect and prevent magic numbers and strings in code.

In JavaScript land, one example is ESLint, a static code analysis tool that can be configured to flag any hard-coded values in code.

Code reviews can also help identify magic numbers and strings and encourage developers to refactor them into constants or enums.

Final Thoughts

Magic numbers and strings can be problematic in code, making it harder to understand, maintain, and debug. The best way to avoid them is to use constants or enums with meaningful names.

Refactoring existing code and using tools like ESLint and code reviews can also help prevent the use of magic numbers and strings. By following best practices and avoiding magic numbers and strings, you can create more maintainable and understandable code.

© 2023 by Dev Discovers. All rights reserved.
Theme by LekoArts