Magic Numbers are literal numeric values that are used directly in code without a clear explanation of their meaning.
For example:
function calculatePrice(total) {
if (total > 1000) {
return total * 0.9; // 0.9 is a magic number
} else {
return total * 0.95; // 0.95 is another magic number
}
}
In this example, the numbers 0.9
and 0.95
are magic numbers because their meaning is not clear. If someone else reads this code in the future, it will be difficult to understand their significance without additional context.
Similarly, Magic Strings are literal string values that are used directly in code without a clear explanation.
For example:
function getErrorMessage(code) {
switch (code) {
case "ERR001":
return "Connection Error"; // "ERR001" is a magic string
case "ERR002":
return "Authentication Error"; // "ERR002" is another magic string
default:
return "Unknown Error";
}
}
Resources:
https://softwareengineering.stackexchange.com/questions/365339/what-is-wrong-with-magic-strings
https://dev.to/ruben_alapont/magic-numbers-and-magic-strings-its-time-to-talk-about-it-ci2