r/ProgrammerTIL • u/Thijmenn • Jan 02 '23
Other Magic Numbers Are Problematic (Use Explanatory Constants Instead)
Hi everyone,
In one of my recent programming seminars we had a discussion about so-called "magic numbers", which refers to the anti-pattern of using numbers directly in source code. My professor demonstrated that this habit, although subtle, can have a noticeable negative impact on the readability of your code, in addition to making it harder to refactor and detect errors while programming. Instead he proposed the use of "explanatory constants", which basically means that you assign (most) numeric literals to an adequately named constant that conveys the number's semantic meaning.
I find the topic particularly interesting because I value readable and well thought-out code (like most of us do) and thus decided to make a video on the topic:
Hopefully the presented information is useful to someone on this subreddit.
View all comments
Show parent comment
3
u/dreamer_ Jan 02 '23 edited Jan 02 '23
For C - you are correct, macro definitions are actually canonical way of doing this - but you probably should do it like this:
In some situations (e.g. if you want to limit the visibility scope of this define), you might prefer to create a global const variable in .c file, as compiler will optimize it.
For modern C++, it's better to use
constexprvariables - as it explicitly communicates your intention:For Rust, keyword
constalso communicates that you want the value to be calculated at compile time.In dynamic languages, like Python - conventionally you place variable at module level and that's it - it will very likely be optimized as well.