Skip to content

Latest commit

 

History

History
114 lines (63 loc) · 3.97 KB

File metadata and controls

114 lines (63 loc) · 3.97 KB

Code Smell 02 - Constants and Magic Numbers

Code Smell 02 - Constants and Magic Numbers

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.

Problems

  • Coupling

  • Low testability

  • Low readability

Solutions

  1. Rename the constant with a semantic and name (meaningful and intention revealing).

  2. Replace constants with parameters, so you can mock them from the outside.

  3. The constant definition is often a different object than the constant (ab)user.

Examples

  • Algorithms Hyper Parameters

Sample Code

Wrong

<?

function energy($mass) {
    return $mass * (299792 ** 2)
}

Right

# Storing magnitudes without units is another smell
class PhysicsConstants
   LIGHT_SPEED = 299792458.freeze
end

def energy(mass)
    mass * PhysicsConstants::LIGHT_SPEED ** 2
end

Detection

Many linters can detect number literals in attributes and methods.

Tags

  • Hard coded

  • Constants

Conclusion

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.

Relations

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

More Info

Refactoring Guru

How to Decouple a Legacy System

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

Software Engineering Great Quotes


This article is part of the CodeSmell Series.

How to Find the Stinky Parts of your Code