Article 68EXH CodeSOD: Constantly Finding Magic

CodeSOD: Constantly Finding Magic

by
Remy Porter
from The Daily WTF on (#68EXH)

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.

otter-icon.png [Advertisement] Otter - Provision your servers automatically without ever needing to log-in to a command prompt. Get started today!
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments