Photo by Dollar Gill on Unsplash
Kotlin Code Smell 001 - Constants and Magic Numbers
A method makes calculations with many numbers without describing their semantics
Play this article
TL;DR: Avoid Magic numbers without explanation. We don't know their source and are afraid to change 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.
A constant definition is often a different object than the constant (ab)user.
Examples
- Algorithms Hyper Parameters
Sample Code
Wrong
fun energy(mass: Double) = (mass * 299792458).pow(2)
Right
typealias MetersPerSeconds = Int
// We're using here the specific unit of measure to avoid yet another code smell
const val LIGHT_SPEED: MetersPerSeconds = 299792458
fun energy(mass: Double) = (mass * LIGHT_SPEED).pow(2)