Refactoring 003 — Extract Constant
You need to use some values explaining their meaning and origin
TL;DR: Name all your magic numbers
Problems Addressed 😔
Readability
Complexity
Code Reuse
Related Code Smells 💨
Code Smell 02 - Constants and Magic Numbers
Steps 👣
Move the constant code fragment to a constant declaration
Replace the values with a reference to the constant.
Sample Code 📖
Before 🚨
double energy(double mass) {
return mass * 300.000 ^ 2;
}After 👉
// 1. Move the constant code fragment to a constant declaration
final double LIGHT_SPEED = 300.000;
double energy(double mass) {
// 2. Replace the old code with a reference to the constant.
return mass * LIGHT_SPEED ^ 2;
}Type 📝
[X] Automatic
Many IDEs support this safe refactoring
Safety 🛡️
This is a safe refactoring.
Why is the Code Better? ✨
Constant names add meaning to our code.
Magic numbers are difficult to understand and change.
Code must be as declarative as possible.
How Does it Improve the Bijection? 🗺️
Every constant you name creates a clear one-to-one mapping between intent and value. That’s bijection.
A raw number like 86400 might mean seconds in a day, but it forces readers to compute that.
Naming it SECONDS_IN_A_DAY makes the mapping explicit.
You remove ambiguity, and readers don’t have to reverse-engineer your logic.
That’s how you keep code understandable at a glance.
Refactor with AI 🤖
Suggested Prompt: 1. Move the constant code fragment to a constant declaration 2. Replace the values with a reference to the constant.
Without Proper Instructions 📵
With Specific Instructions 👩🏫
Tags 🏷️
Readability
Level 🔋
[X] Beginner
Related Refactorings 🔄
Refactoring 008 - Convert Variables to Constant
Credits 🙏
This article is part of the Refactoring Series
How to Improve your Code With easy Refactorings
Refactorings are amazing to grow and improve our code





