Refactoring 003 - Extract Constant

Refactoring 003 - Extract Constant

You need to use some values explaining their meaning and origin

Maxi Contieri
·Jan 2, 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
  • Why code is better?
  • Tags
  • Related Refactorings
  • Credits

TL;DR: Name all your magic numbers

Problems Addressed

  • Readability

  • Complexity

  • Code Reuse

Related Code Smells

Steps

  1. Move the constant code fragment to a constant declaration

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

Why code is better?

Constant names add meaning to our code.

Magic numbers are difficult to understand and change.

Code must be as declarative as possible.

Tags

  • Readability

Related Refactorings

Credits

Image by Tumisu from Pixabay


This article is part of the Refactoring Series.

 
Share this

Impressum

Technical Opinions are my own. I don't have the revealed truth.

Software Design is a creative activity. These are hints and not rigid rules.

I write on BackEnd Business Systems and OOP Design. My advice/experience might not suit other systems.

You can write me at info(at)maximilianocontieri.com