DEV Community

Cover image for Refactoring 003 - Extract Constant
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

4 2

Refactoring 003 - Extract Constant

You need to use some values explaining their meaning and origin

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;
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay