Code Smell 02 - Constants and Magic Numbers

Code Smell 02 - Constants and Magic Numbers

Maxi Contieri

Published on Oct 20, 2020

1 min read

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

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.


  • Coupling
  • Low testability
  • Low readability


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.


  • Algorithms Hyper Parameters

Sample Code



function energy($mass) {

    return $mass * (300000 ^ 2);

function energy($mass) {



Many linters can detect number literal in attributes and methods.


  • Hard coded
  • Constants

More info


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

Share this