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
·Nov 30, 2022·
1 min read
Play this article
TL;DR: Avoid Magic numbers without explanation. We don't know their source and are afraid to change them.
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.
- Algorithms Hyper Parameters
fun energy(mass: Double) = (mass * 299792458).pow(2)
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)