Code Smell | Magic Numbers

susomejias

Jesús Mejías Leiva

Posted on August 16, 2022

Code Smell | Magic Numbers

Hello, today we are back with the code smells refactoring series and in this case we are going to talk about code smell called Magic Numbers, this code smell can be detect when we use a number that lacks the proper semantics.


Cause

Numbers lacking semantics make calculations harder to read.


Example

As we can see in the following example we have 2 magic numbers that are quite easy to detect since it is really complex to know what type of calculation we are performing simply by observing these values: 4.50 and 0.21

function calculateTotal(subtotal) {
  const total = subtotal + 4.50;
  return total + (total * 0.21);
}
Enter fullscreen mode Exit fullscreen mode

Solution

By extracting both numbers to constants and giving them semantics we can see that the code is much more readable.

const SHIPPING_FEE = 4.50;
const SALES_TAX = 0.21;

function calculateTotal(subtotal) {
  const total = subtotal + SHIPPING_FEE;
  return total + (total * SALES_TAX);
}
Enter fullscreen mode Exit fullscreen mode

Benefits

  • Improvement the readability and maintainability of the code.
  • You will make the next person who needs to go through that part of the code very happy 😋 jiji

Thanks for reading me 😊

💖 💪 🙅 🚩
susomejias
Jesús Mejías Leiva

Posted on August 16, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Code Smell | Magic Numbers
refactorit Code Smell | Magic Numbers

August 16, 2022

Top 10 practices I hate in C++
cpp Top 10 practices I hate in C++

September 29, 2020

When Should You Refactor Your Code?
refactorit When Should You Refactor Your Code?

August 13, 2020

Using Dictionaries to refactor
refactorit Using Dictionaries to refactor

May 18, 2020