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.
FOUR_HUNDRED_FOUR = 404
. I worked on another project where they were militant about using constant strings instead of literals, so they had dozens of lines in code that looked like,DATABASE = "database"
1024
, because otherwise your dev team will spend all it's time arguing about wether it is "kilobytes" or "kibibytes".#define
KIBI
as 1024,MEBI
as 1024*1024…ZERO=0, ONE=1, TWO=2
and when programs are ported to other languages (or the programmers don’t change behavior when switching their language) you’ll see it there too and you have to pray that never someone change it toONE=2
…