CodeSOD: Constantly Finding Magic

We constantly see developers finding… creative solutions to the requirement that they avoid magic numbers in their code. Refactoring to define a constant is just too hard, apparently.

Today, Maklemore sends us a short snippet that neatly solves the problem of magic numbers by making sure the number isn't a number, at least to start:

if (eventToValidate.Location.StartMilePoint.HasValue
	&& eventToValidate.Location.StartMilePoint.Value > decimal.Parse("999.9999"))
	validationResult.AddErrorMessage("The From Milepoint cannot be greater than 999.9999.");
if (eventToValidate.Location.EndMilePoint.HasValue
	&& eventToValidate.Location.EndMilePoint.Value > decimal.Parse("999.9999"))
	validationResult.AddErrorMessage("The To Milepoint cannot be greater than 999.9999.");

Technically, "999.9999" isn't a magic number. It's a magic string. You might argue that's a distinction without difference, and you'd likely be right.

What makes this snippet extra fun is the fact that we can see the constant referenced on essentially every line of code in this block and nobody thought for even a second that maybe it should be turned into a constant.

But at least it's not a magic number.

[Advertisement] Otter - Provision your servers automatically without ever needing to log-in to a command prompt. Get started today!

This post originally appeared on The Daily WTF.

Leave a Reply

Your email address will not be published. Required fields are marked *