Say “No” to Magic Numbers
One thing it’s easy to forget when writing code is that someone is going to have to read it without knowing what’s going through your head when you write it. Often, that person is simply you six months later. And (not) surprisingly, future-you is probably going to look at that code and be unable to remember exactly what past-you was thinking when you wrote it.
One of the most annoying things can be coming across a line like this one I found in the Workbench class of a game I’m building:
public Tile GetSpawnTile()
return Region.GetTileAt(tile.X + 2, tile.Y + 1);
Huh? Why am I adding these apparently random numbers to the tile position of my workbench? Where do they come from? If I change one will it fix the problem I’m currently having or will everything blow up in my face?
I wrote this code over 9 months ago, and I couldn’t remember exactly what those numbers were for. So I spent some time changing them and testing what happened, and figured out that they were the offset for where my workbenches’ output was supposed to show up in relation to the main tile of the workbench.
So I created a new variable on the class:
private Vector2 _outputSpawnOffset;
And changed the return of the method to:
return Region.GetTileAt(tile.X + _outputSpawnOffset.x, tile.Y + _outputSpawnOffset.y);
A little more verbose, but now it doesn’t matter when I come back to it I’ll be able to tell instantly what those values represent. And it has the added advantage that if I need to reference the
_outputSpawnOffset if another method further down the track I can call on the variable and know that both methods will always be using the same values.
This was, of course, an incredibly simplified example. It does illustrate a very real and common situation though. So the next time you’re tempted to just throw a number into an equation without some way of letting a future reader know what it is, just say “no”!