cover-img

Code Smell 02 - Constants and Magic Numbers

A method makes calculations with lots of numbers without describing their semantics

12 July, 2022

7

7

0

TL;DR: Avoid Magic numbers without explanation. We don't know their source and we are very afraid of changing them.

Problems

  • Coupling
  • Low testability
  • Low readability

Solutions

  1. Rename the constant with a semantic and name (meaningful and intention revealing).

  2. Replace constants with parameters, so you can mock them from the outside.

  3. The constant definition is often a different object than the constant (ab)user.

Examples

  • Algorithms Hyper Parameters

Sample Code

Wrong




Detection

Many linters can detect number literals in attributes and methods.

Tags

  • Hard coded
  • Constants

More info

Credits

Photo by Kristopher Roller on Unsplash


In a purely functional program, the value of a [constant] never changes, and yet, it changes all the time! A paradox!

Joel Spolsky

https://maximilianocontieri.com/software-engineering-great-quotes


This article is part of the CodeSmell Series.

7

7

0

Maxi Contieri

Buenos Aires, Argentina

🎓Learn something new every day.📆 💻CS software engineer 👷coding👨🏽‍🏫teaching ✍🏾writing 🎨Software Design 🏢SOLID 🌉TDD 👴Legacy 💩Code Smells

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

© Copyright 2024. Showcase Creators Inc. All rights reserved.