If I see a Variable that doesn't change. I call that variable a constant
TL;DR: Be explicit on what mutates and what doesn't.
Problems Addressed ๐
- Mutability
- Code Optimization
Related Code Smells ๐จ
https://hackernoon.com/how-to-find-the-stinky-parts-of-your-code-part-xxxii?embedable=true
https://hackernoon.com/how-to-find-the-stinky-parts-of-your-code-part-xxvi?embedable=true
https://hackernoon.com/how-to-find-the-stinky-parts-of-your-code-part-xxiv?embedable=true
Context ๐ฌ
Variables that never change their value are not really variables.
Theyโre constants pretending to be mutable state.
When we declare something as a variable, we tell the reader (and the compiler) to expect change.
If that change never happens, weโre sending misleading signals about what the code actually does.
Converting these to constants shrinks the state space a developer must track.
A constant signals that a value wonโt change, preventing accidental reassignments and letting the compiler optimize better.
Itโs honest: if something shouldnโt mutate, donโt let it.
Steps ๐ฃ
- Find the scope of the variable
- Define a constant with the same scope
- Replace the variable
Sample Code ๐ป
Before ๐จ
let lightSpeed = 300000;
var gravity = 9.8;
// 1. Find the scope of the variable
// 2. Define a constant with the same scope
// 3. Replace the variable
After ๐
const lightSpeed = 300000;
const gravity = 9.8;
// 1. Find the scope of the variable
// 2. Define a constant with the same scope
// 3. Replace the variable
// If the object is compound,
// we might need Object.freeze(gravity);
Type ๐
[X] Automatic
IDEs can check if a variable is written but never updated.
Safety ๐ก๏ธ
This is a safe refactoring.
Why is the Code Better? โจ
Code is more compact and declares intent clearly.
Take it further with language-specific operators likeย const,ย final, orย let.
The scope becomes obvious at a glance.
How Does it Improve the Bijection? ๐บ๏ธ
This refactoring improvesย bijectionย by making it clear what mutates and what doesn't.
In the real world, most values don't change. They're constants.
Declaring them as variables createsย couplingย between what we're thinking and how we wrote it.
Constants remove that gap and align the code with the actual domain.
Tags ๐ท๏ธ
- Mutability
Level ๐
[X] Beginner
Related Refactorings ๐
https://hackernoon.com/improving-the-code-one-line-at-a-time?embedable=true
Refactor with AI ๐ค
Suggested Prompt: 1. Find the scope of the variable.2. Define a constant with the same scope.3. Replace the variable
Without Proper Instructions ๐ต
With Specific Instructions ๐ฉโ๐ซ
See also ๐
This article is part of the Refactoring Series
https://maximilianocontieri.com/how-to-improve-your-code-with-easy-refactorings?embedable=true
https://maximilianocontieri.com/how-to-improve-your-code-with-easy-refactorings
