Code Smell 02 - Constants and Magic Numbers

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.

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

Detection

Many linters can detect number literal in attributes and methods.

Tags

  • Hard coded
  • Constants
  • Repeated Code

Conclusion

Replace magic numbers for meaningful names. The code maintainer will be aware of its meaning. It might be yourself.

More info

Credits

Photo by Kristopher Roller on Unsplash


This article is part of the CodeSmell Series.

No Comments Yet