Code Smell 02 - Constants and Magic Numbers
12 July, 2022
7
7
0
Contributors
TL;DR: Avoid Magic numbers without explanation. We don't know their source and we are very afraid of changing them.
Problems
- Coupling
- Low testability
- Low readability
Solutions
-
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.
Examples
- Algorithms Hyper Parameters
Sample Code
Wrong
Right
Detection
Many linters can detect number literals in attributes and methods.
Tags
- Hard coded
- Constants
More info
Credits
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
https://maximilianocontieri.com/software-engineering-great-quotes
This article is part of the CodeSmell Series.