A method makes calculations with lots of numbers without describing their semantics
TL;DR: Avoid Magic numbers without explanation. We don't know their source and we are very afraid of changing them.
-
Low testability
-
Low readability
-
Rename the constant with a semantic and name (meaningful and intention revealing).
-
Replace constants with parameters, so you can mock them from the outside.
-
The constant definition is often a different object than the constant (ab)user.
- Algorithms Hyper Parameters
<?
function energy($mass) {
return $mass * (299792 ** 2)
}
# 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
-
Constants
You should address and remove your magic numbers to safeguard your code's readability, maintainability, and testability.
Clear, semantic naming and decoupling constants from their consumers are essential steps toward crafting cleaner, more resilient software.
Every magic number you replace with intention-revealing logic is a step away from brittle code and closer to robust, professional craftsmanship.
Don't let numbers dictate your code; define their purpose and context instead.
Code Smell 158 - Variables not Variable
Code Smell 127 - Mutable Constants
Code Smell 06 - Too Clever Programmer
Code Smell 162 - Too Many Parentheses
Code Smell 198 - Hidden Assumptions
Code Smell 202 - God Constant Class
How to Decouple a Legacy System
Photo by Kristopher Roller on Unsplash
In a purely functional program, the value of a [constant] never changes, and yet, it changes all the time! A paradox!
Joel Spolsky
Software Engineering Great Quotes
This article is part of the CodeSmell Series.