DEV Community

Discussion on: Avoid Magic Numbers to Increase Code Readability

Collapse
 
lexlohr profile image
Alex Lohr

A number is only "magic" if it has a meaning beyond its value, e.g. measurements, limitations, positions, etc.

Especially your example of 2**whatever can be extremely magic, if you use it to store flags inside an integer, like for example TOS inside IP headers:

const parseTos = (tos) => [tos & 7, !!(tos & 8), !!(tos & 16), !!(tos & 32)]

const PRECEDENCE = 7 // bit 0-2
const LOW_DELAY = 8
const HIGH_THROUGHPUT = 16
const HIGH_RELIABILITY = 32

const parseTosWithoutMagic = (tos) => [
  tos & PRECEDENCE,
  !!(tos & LOW_DELAY),
  !!(tos & HIGH_THROUGHPUT),
  !!(tos & HIGH_RELIABILITY),
]
Enter fullscreen mode Exit fullscreen mode

As you can see, the code is more verbose, but also far easier to understand.

Collapse
 
paddy3118 profile image
Paddy3118

A number is only "magic" if it has a meaning beyond its value, e.g. measurements, limitations, positions, etc.

I agree in your particular example, but take, for example indexing a Python list from the beginning - You see, and what is readable is to use integer 0. Want all odd members, use [1: - 1: 2]; all but the last, [:-2]. Some of these constants with meaning are baked into the Luton documentation.
These 'suggestions' should be known, but one needs to read a lot of Python to see when they are and are not applied to good effect. Definitely not backed into a linter for example, or taught as hard and fast rules.