DEV Community

loading...
Cover image for Code Smell 02 - Constants and Magic Numbers

Code Smell 02 - Constants and Magic Numbers

mcsee profile image Maxi Contieri Originally published at Medium Updated on ・1 min read

This article is part of the CodeSmell Series.

Description

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

Problems

  • Coupling
  • Low testability
  • Low readability
  • Repeated Code

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

Right

Detection

Many linters can detect number literal in attributes and methods.

Relations

Tags

  • Hard coded
  • Constants
  • Repeated Code

More info

Photo by Kristopher Roller on Unsplash

Discussion (0)

pic
Editor guide