Jonathan Bennett

Numbers in Your Code are Red Flags

Number in your code are red flags.

For instance, what does “12” mean? this could be used for a dozen in a recipe app, months of the year for a Gregorian calendar, or number of disciples in a religion app.

I always raise a flag when I see a number.

Where this bit me recently was with an invitation system. Invites expired after 2 days, but that was going to be changed to a week. This had to be updated in 3 places: the invite link code, and the HTML and plain text templates.

This was a minor change, only introducing a new variable with the duration:

class Invitation
	EXPIRY_DELAY = 7.days
	# …
end

With this change, what the number 7 means is now explicit, it’s related to when the invite will expire, it’s now clear that we are working in days, not hours, and will be updated globally if we change it in one location.