Refactoring 003 — Extract Constant

Image by Tumisu from Pixabay

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

This article is part of the Refactoring Series.

--

--

--

I’m a senior software engineer specialized in declarative designs. S.O.L.I.D. and agile methodologies fan. Maximilianocontieri.com

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

What does Alchemy do in Web3?

CS371p Spring 2021: Nayan Shashidhar

I attended the GDG SSA Community Summit

Best practices on writing monolithic services in Go

What writing a book taught me about failure

How to add a news ticker to your live stream

How to buy the best mobile phone for you using this MCDM ‘Notion Template’

Notion Template for Decision Making (MCDM/MADM) using TOPSIS

Profiling CPython at Instagram

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Maximiliano Contieri

Maximiliano Contieri

I’m a senior software engineer specialized in declarative designs. S.O.L.I.D. and agile methodologies fan. Maximilianocontieri.com

More from Medium

Code Smell 107 — Variables Reuse

Stop Playing Code Golf At Work

Defensive Programming Techniques

Open-Closed Principle is nothing about the code