Magic Numbers are numeric values used directly in code without explanation or context. They are hard-coded into the code rather than being represented by a named constant or variable, which can make the code harder to understand and maintain.
Here are some key features and issues associated with Magic Numbers:
Lack of Clarity: The meaning of a Magic Number is often not immediately clear. Without a descriptive constant or variable, it's not obvious why this specific number is used or what it represents.
Maintenance Difficulty: If the same Magic Number is used in multiple places in the code, updating it requires changing every instance, which can be error-prone and lead to inconsistencies.
Violation of DRY Principles (Don't Repeat Yourself): Repeatedly using the same numbers in different places violates the DRY principle, which suggests centralizing reusable code.
Example of Magic Numbers:
int calculateArea(int width, int height) {
return width * height * 3; // 3 is a Magic Number
}
Better Approach: Instead of using the number directly in the code, it should be replaced with a named constant:
const int FACTOR = 3;
int calculateArea(int width, int height) {
return width * height * FACTOR;
}
In this improved example, FACTOR
is a named constant that makes the purpose of the number 3
clearer. This enhances code readability and maintainability, as the value only needs to be changed in one place if necessary.
Summary: Magic Numbers are direct numeric values in code that should be replaced with named constants to improve code clarity, maintainability, and understanding.