You need to use some values explaining their meaning and origin
TL;DR: Name all your magic numbers
-
Readability
-
Complexity
-
Code Reuse
Code Smell 02 - Constants and Magic Numbers
-
Move the constant code fragment to a constant declaration
-
Replace the values with a reference to the constant.
double energy(double mass) {
return mass * 300.000 ^ 2;
}
// 1. Move the constant code fragment to a constant declaration
final double LIGHT_SPEED = 300.000;
double energy(double mass) {
// 2. Replace the old code with a reference to the constant.
return mass * LIGHT_SPEED ^ 2;
}
[X] Automatic
Many IDEs support this safe refactoring
Constant names add meaning to our code.
Magic numbers are difficult to understand and change.
Code must be as declarative as possible.
This is a safe refactoring.
- Readability
Refactoring 002 - Extract Method
This article is part of the Refactoring Series.