Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Code Smell | Magic Numbers
Product Hackers profile imageJesús Mejías Leiva
Jesús Mejías Leiva forProduct Hackers

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

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);}
Enter fullscreen modeExit 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 😊

Top comments(3)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
mcsee profile image
Maxi Contieri
Learn something new every day. - I am a senior software engineer working in industry, teaching and writing on software design, SOLID principles, DDD and TDD.
  • Location
    Buenos Aires
  • Education
    Computer Science Degree at Universidad de Buenos Aires
  • Pronouns
    He/Him
  • Work
    Senior Software Engineer at Avature
  • Joined

Nice!!!

CollapseExpand
 
susomejias profile image
Jesús Mejías Leiva
Mid-Frontend Developer at Product Hackers (Córdoba, Spain)
  • Location
    Córdoba
  • Education
    Web Developer
  • Work
    Mid-Frontend Developer at Product Hackers
  • Joined

Thanks for you comment Maxi 😊

CollapseExpand
 
novacat25 profile image
NovaCat
  • Joined
• Edited on• Edited

This is the thing that I've got feedbacks while doing the last project,
And this article reminds me about that too👍

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

If you want to know more about us, don't hesitate contacting through our website.

More fromProduct Hackers

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp