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"
– sea-rob Dec 17 '14 at 20:251024
, because otherwise your dev team will spend all it's time arguing about wether it is "kilobytes" or "kibibytes". – Gort the Robot Dec 17 '14 at 20:51#define
KIBI
as 1024,MEBI
as 1024*1024… – ysdx Dec 18 '14 at 00:58ZERO=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
… – Holger Dec 18 '14 at 09:29Mathematical constants can't change
- that's true, although sometimes the precision of their approximation can change. That's why we typically use aPi
constant rather than 3.14, or 3.14159 or... yeah, that's the point :) – Konrad Morawski Dec 18 '14 at 22:29ONE=2
isn't as bad as1=2
? – user1686 Dec 19 '14 at 11:33var kBval = byteVal >> 10;
? – Noctis Skytower Dec 19 '14 at 14:09Information
. In an OO language that would be a class with methods to output readings in specific prefix, or as a string with automatically-chosen prefix ("human-readable"). But the conversion by multiplication / division should never appear anywhere openly. (Admittedly, what I'm describing is still a bit of a utopia.) – leftaroundabout Dec 20 '14 at 13:09