If I see a Variable that does not change. I call that variable a constant
TL;DR: Be explicit on what mutates and what does not.
-
Code Optimization
Code Smell 158 - Variables not Variable
Code Smell 127 - Mutable Constants
Code Smell 116 - Variables Declared With 'var'
-
Find the scope of the variable
-
Define a constant with the same scope
-
Replace the variable
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
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);
[X] Automatic
Our IDEs can check if a variable is written but never updated.
This is a safe refactor.
Code is more compact and declarative.
We can make and step further and use operators like var, let, const, etc.
The scope is more clear.
- Mutability
Refactoring 003 - Extract Constant
This article is part of the Refactoring Series.