DEV Community

Discussion on: local constants vs comments

Collapse
 
bloodgain profile image
Cliff

The second option is objectively superior. It's not just a readability thing, though I would argue it's more fluid/natural and thus more readable.

There's a reason almost every linter will flag "magic numbers" like the '2' in your first example. Not only does labeling these with names make the code read more clearly, it's less error-prone. What happens when the magic value changes from 2 to 3? Somebody changes the value, but forgets to update the comment, because comments are often mentally invisible when working with code. Maybe code review catches it, maybe it doesn't. Also, almost any magic number like this will appear in many places, so the local const should and will be promoted to a higher scope; the second style prepares for that with code.

Lastly, the second version is self-documenting, with all the benefits that come with that (which have been discussed ad nauseum elsewhere, so I won't).

Collapse
 
peledzohar profile image
Zohar Peled

Good reasoning!