Code Smell 02 - Constants and Magic Numbers

Code Smell 02 - Constants and Magic Numbers

Leader 1 47 114
calendar_todayschedule4 min read

A method makes calculations with lots of numbers without describing their semantics

TL;DR: Avoid Magic numbers without explanation. You don't know their source and are very afraid of changing them.

Problems

  • Coupling

  • Low testability

  • Low readability

Solutions

1) Rename the constant to a meaningful, intention-revealing name.

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.

Refactorings ⚙️

https://maximilianocontieri.com/refactoring-003-extract-constant

https://maximilianocontieri.com/refactoring-025-decompose-regular-expressions

Examples

  • Algorithms Hyper Parameters

Context

Magic numbers are literal values embedded directly into your code without explanation.

They often appear in algorithms, configuration rules, or business logic as unexplained numeric values.

At first, they might feel faster to write, but over time they turn into hidden assumptions that no one remembers.

Future maintainers must guess their meaning, increasing the risk of errors when the values need to change.

Constants help, but naming them meaningfully and placing them in the right context is what turns a magic number into a reliable, self-explanatory part of your code.

Sample Code

Wrong

<?

function energy($mass) {
    return $mass * (299792 ** 2)
}
# Storing magnitudes without units is another smell
class PhysicsConstants
   LIGHT_SPEED = 299792458.freeze
end

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

Detection

[X] Semi-Automatic

Many linters can detect number literals in attributes and methods.

Tags ️

  • Declarative Code

Level

[X] Beginner

Why the Bijection Is Important ️

When you replace a magic number with a named constant, you create a bijection between the value and its meaning.

This one-to-one relationship ensures every numeric value has a clear, unambiguous purpose in your system.

Without it, the same number could be reused for different reasons, leading to confusion and accidental coupling.

A bijection between meaning and value makes the code easier to navigate, test, and evolve without fear of breaking unrelated parts.

AI Generation

Large Language Models can introduce magic numbers when generating code, especially in examples or algorithm implementations.

Treat AI-generated values with the same suspicion you would any human-written literal.

Always check if the number is a placeholder, a real-world constant, or an algorithmic parameter, and replace it with a meaningful name before merging it into production code.

AI Detection

Code reviewers should stay alert to magic numbers introduced by AI tools, which often lack context or semantic naming.

Automated linters can flag number literals, but human insight is critical to understand if a value requires refactoring into a named constant.

Keep your eyes open for AI-generated black box numbers that might slip past initial checks but can cause maintenance headaches later.

Try Them!

Remember: AI Assistants make lots of mistakes

Suggested Prompt: Replace Magic numbers with constants

Without Proper Instructions With Specific Instructions
ChatGPT ChatGPT
Claude Claude
Perplexity Perplexity
Copilot Copilot
You You
Gemini Gemini
DeepSeek DeepSeek
Meta AI Meta AI
Grok Grok
Qwen Qwen

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 ❤️

https://maximilianocontieri.com/code-smell-158-variables-not-variable

https://maximilianocontieri.com/code-smell-127-mutable-constants

https://maximilianocontieri.com/code-smell-06-too-clever-programmer

https://maximilianocontieri.com/code-smell-162-too-many-parentheses

https://maximilianocontieri.com/code-smell-198-hidden-assumptions

https://maximilianocontieri.com/code-smell-202-god-constant-class

More Information

https://refactoring.guru/es/replace-magic-number-with-symbolic-constant

https://maximilianocontieri.com/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

https://maximilianocontieri.com/software-engineering-great-quotes


This article is part of the CodeSmell Series.

https://maximilianocontieri.com/how-to-find-the-stinky-parts-of-your-code

1 Comment

1 vote
🔥 Join developers growing publicly
Share your knowledge, build in public, and grow your developer presence with a global community.

More Posts

Tuesday Coding Tip 02 - Template with type-specific API

Jakub Neruda - Mar 10

Code Smell 01 - Anemic Models

Maxi Contieri - Nov 12, 2025

Code Smell 320 - Vanity Coverage

Maxi Contieri - Jun 23

Code Smell 319 - Hardcoded Stateless Properties

Maxi Contieri - Apr 9

Code Smell 17 - Global Functions

Maxi Contieri - Feb 28
chevron_left
6.6k Points162 Badges
Buenos Aires, Argentinamaximilianocontieri.com
68Posts
3Comments
4Connections
Learn something new every day
Software Engineer and author of Clean Code Cookbook (https://amzn.to/4... Show more

Related Jobs

View all jobs →

Commenters (This Week)

1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!