How to Find the Stinky Parts of Your Code: 249 - Constants as Numbers

25 Apr 2024

You map concepts to optimized numbers

TL;DR: Use real-world constants as constants


  • Bijection Violation
  • Debugging
  • Premature Optimization
  • Maintainability
  • Type Safety
  • Limited Extensibility


  1. Use descriptive string constants
  2. Use Enums
  3. Create A Polymorphic Hierarchy


Numeric constants representing real-world concepts lack readability and make your code harder to understand.

It's not clear what each number represents.

if you need to add more constants in the future or change the order, you'll have to update all occurrences of these numeric constants manually.

New values can introduce errors and make maintenance more difficult.

Saving attributes as integers to improve the persistence performance or space is a clear signal of Premature Optimization.

Sample Code


public const FORMAT_JPG = 1;
public const FORMAT_GIF = 2;
public const FORMAT_PNG = 3;


public const string FORMAT_JPG = "JPG";
public const string FORMAT_GIF = "GIF";
public const string FORMAT_PNG = "PNG";

// OR

public enum ImageFormat


  • Semi-Automatic

You can tell your linters to warn you about this usage, but they can show you some false positives.


  • Readability


  • Beginner

AI Generation

No models create this premature optimization problem when prompted to list constants.

AI Detection

ChatGPT and Gemini detected this as a mistake.


After this correction, your code will be cleaner readable, and self-explanatory for debugging.

You can read it and It's clear what each constant represents.

If you need to add more formats or change the order, you should update the enumeration definition without affecting the rest of the code.

IDEs with auto-completion and error checking will give you better support to work with enums.


Code Smell 02 - Constants and Magic Numbers

Code Smell 110 - Switches With Defaults

Code Smell 20 - Premature Optimization

More Info

How to Get Rid of Annoying IFs Forever


Code Smells are my opinion.


Photo by Markus Krisetya on Unsplash

Forget this world and all its troubles and if possible its multitudinous Charlatans - everything in short but the Enchantress of Numbers.

Ada Lovelace

Software Engineering Great Quotes

This article is part of the CodeSmell Series.

How to Find the Stinky Parts of your Code