Clean code and magic numbers

Robert C. Martin’s Clean Code is justly revered, but the urge to nitpick the wisdom of one’s elders and betters is sometimes hard to resist. I therefore present for consideration his heuristic G25: ‘replace magic numbers with named constants’. The heuristic itself is more or less incontrovertible: as Martin writes, it’s ‘probably one of the oldest rules in software development’. The more interesting part comes when he gives examples of potential exceptions to the rule:

double milesWalked = feetWalked/5280.0;
int dailyPay = hourlyRate * 8;
double circumference = radius * Math.PI * 2;

Do we really need the constants FEET_PER_MILE, WORK_HOURS_PER_DAY, and TWO in the above examples? … in the FEET_PER_MILE case, the number 5280 is so very well known and so unique a constant that readers would recognize it even if it stood alone on a page with no context surrounding it.

– at which point American readers nod sagely, and the rest of the world throws up its hands and shouts ‘WHAT!?’.

I would guess that Martin in fact knows that most of the world uses the metric system, and if pressed on the point would concede that ‘so very well known’ only applies to the USA. (Even in the UK, where miles are still used for road distances, I suspect that few people have memorized the conversion factor to feet.) It’s an understandable oversight, though: I can easily imagine incorporating the magic number 1000 in a metres / kilometres conversion, forgetting that there may be American (or Liberian, or Burmese) programmers to whom this is not self-evident.

In the end, Martin’s oversight here just shows that the rule is even stronger than he claims: it might be expanded to ‘replace magic numbers with named constants, even when you’re convinced that this is a case in which it’s not necessary to replace magic numbers with constants’. This is particularly true now that source code is being more widely shared than ever before, and programming is being done by people from an ever-larger variety of backgrounds. Especially in open source projects, you can assume very little about the people who will be reading your code in the future.