Refactoring 008 - Convert Variables to Constant

Refactoring 008 - Convert Variables to Constant

If I see a Variable that does not change. I call that variable a constant

Maxi Contieri
·Aug 26, 2022·

1 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • Problems Addressed
  • Related Code Smells
  • Steps
  • Sample Code
  • Type
  • Safety
  • Why code is better?
  • Tags
  • Related Refactorings
  • See also

TL;DR: Be explicit on what mutates and what does not.

Problems Addressed

Related Code Smells

Steps

  1. Find the scope of the variable

  2. Define a constant with the same scope

  3. 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

Our IDEs can check if a variable is written but never updated.

Safety

This is a safe refactor.

Why code is better?

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.

Tags

  • Mutability

Related Refactorings

See also


This article is part of the Refactoring Series.

 
Share this