Yonatan Karp-Rudin
Yonatan Karp-Rudin

Follow

Yonatan Karp-Rudin

Follow
Kotlin Code Smell 001 - Constants and Magic Numbers

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

Yonatan Karp-Rudin's photo
Yonatan Karp-Rudin
·Nov 30, 2022·

1 min read

Play this article

Table of contents

  • Problems
  • Solutions
  • Examples
  • Sample Code
  • More Information
  • Credits

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)

More Information

Credits

 
Share this