
Posted on • Edited on • Originally published atblog.susomejias.dev
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 calledMagic 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 have2 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 and0.21
functioncalculateTotal(subtotal){consttotal=subtotal+4.50;returntotal+(total*0.21);}
Solution
By extracting both numbers to constants and giving them semantics we can see that the code is much more readable.
constSHIPPING_FEE=4.50;constSALES_TAX=0.21;functioncalculateTotal(subtotal){consttotal=subtotal+SHIPPING_FEE;returntotal+(total*SALES_TAX);}
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 😊
Top comments(3)

- LocationBuenos Aires
- EducationComputer Science Degree at Universidad de Buenos Aires
- PronounsHe/Him
- WorkSenior Software Engineer at Avature
- Joined
Nice!!!

- LocationCórdoba
- EducationWeb Developer
- WorkMid-Frontend Developer at Product Hackers
- Joined
Thanks for you comment Maxi 😊
For further actions, you may consider blocking this person and/orreporting abuse