TL;DR: Avoid Magic numbers without explanation. We don't know their source and are afraid to change them.
- Low testability
- Low readability
1) Rename the constant with a semantic and name (meaningful and intention revealing).
2) Replace constants with parameters, so you can mock them from the outside.
3) The constant definition is often a different object than the constant (ab)user.
- Algorithms Hyper Parameters
def energy(mass) mass * 299792458 ** 2 end
# Storing magnitudes without units is another smell class PhysicsConstants LIGHT_SPEED = 299792458.freeze end def energy(mass) mass * PhysicsConstants::LIGHT_SPEED ** 2 end
Many linters can detect number literals in attributes and methods.
- Hard coded
In a purely functional program, the value of a [constant] never changes, and yet, it changes all the time! A paradox!
This article is part of the CodeSmell Series.