On a recent project, I needed to convert from bytes to kilobytes kibibyte. The code was straightforward enough:
var kBval = byteVal / 1024;
After writing that, I got the rest of the function working & moved on.
But later on, I started to wonder if I had just embedded a magic number within my code. Part of me says it was fine because the number is a fixed constant and should be readily understood. But another part of me thinks it would have been super clear if wrapped in a defined constant like BYTES_PER_KBYTE
.
So are numbers that are well known constants really all that magical or not?
Related questions:
When is a number a magic number? and Is every number in the code considered a "magic number"? - are similar, but are much broader questions than what I'm asking. My question is focused on well-known constant numbers which is not addressed in those questions.
Eliminating Magic Numbers: When is it time to say "No"? is also related, but is focused on refactoring as opposed to whether or not a constant number is a magic number.