DEV Community

Cover image for Code Smell 02 - Constants and Magic Numbers
Maxi Contieri
Maxi Contieri

Posted on • Edited on • Originally published at maximilianocontieri.com

13 1

Code Smell 02 - Constants and Magic Numbers

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

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

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 outside.

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

Examples

  • Algorithms Hyper Parameters

Sample Code

Wrong

<?

function energy($mass) {

    return $mass * (300000 ^ 2);
}
Enter fullscreen mode Exit fullscreen mode

Right

<?

function energy($mass) {

    return $mass * (LIGHT_SPEED_KILOMETERS_OVER_SECONDS ^ 2);
}
Enter fullscreen mode Exit fullscreen mode

Detection

Many linters can detect number literal 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


This article is part of the CodeSmell Series.

Last update: 2021/05/31

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (1)

Collapse
 
dennysjmarquez profile image
Dennys José Márquez Reyes

🤜🤛🤓

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