askvity

Is 1 a magic number?

Published in Programming Constants 2 mins read

No, 1 is not considered a magic number by default.

Understanding Magic Numbers

The term "magic number" in programming usually refers to a numeric literal used directly in code without a clear explanation of its meaning. This practice is generally discouraged because it can make code harder to understand and maintain. To mitigate this, it's best practice to define such numbers as constants with descriptive names.

Default Exceptions

However, certain numbers are often exempt from being considered magic numbers due to their common and well-understood usage. According to the reference:

  • By default, -1, 0, 1, and 2 are not considered to be magic numbers.

This exception is based on the assumption that these numbers are so frequently used for basic operations (like initialization, indexing, or simple arithmetic) that their meaning is generally clear from context.

Example

Let's illustrate with an example using Python:

# Not considered magic numbers
index = i + 1
result = x * 0

# Considered a magic number (should ideally be a constant)
discounted_price = price * 0.85  # 0.85 should be a constant like DISCOUNT_RATE

In this example:

  • Using 1 to increment the index variable is generally acceptable.
  • Using 0 to zero out the result is also generally acceptable.
  • Using 0.85 directly to calculate a discount rate is not preferable. It would be better to define DISCOUNT_RATE = 0.85 and use price * DISCOUNT_RATE instead. This makes the code more readable and easier to modify if the discount rate changes.

Conclusion

While 1 is often used directly without being flagged as a magic number, good coding practice always favors clarity. If the meaning of 1 is not immediately obvious in a particular context, it is better to define it as a constant for improved readability.

Related Articles