Are Small Coding Tricks Worth It?
September 19, 2009 The following code snippet is part of the PAUSE BUTTON implementation in a video game. The game is paused by setting Time.timeScale to 0 and it is unpaused by setting it back to 1.0.
if (GUI.Button(Rect(25,100,100,30),"PAUSE"))
{
if (Time.timeScale == 1.0)
{
Time.timeScale = 0;
}
else
{
Time.timeScale = 1.0;
}
}
The code is simple and straightforward. The solution is logically consistent with the way most people would naturally think through the problem. But is this the most efficient solution? With just a little more thought, one might come up with something similar to the following solution.
if (GUI.Button(Rect(25,100,100,30),"PAUSE"))
{
Time.timeScale = 1.0 - Time.timeScale;
}
So which one is the better solution?
Before we try to compare the two, let's forget anything concerning speed. The first solution (S1 from now on) has an extra comparison and the second solution (S2) has an added calculation. I don't know which of these will technically be faster, but it doesn't matter. The difference is negligible and both will be blindingly fast.
That being said, let's start comparing the two. Most programmers, including myself, would immediately declare S2 to be the better choice. After all, getting the same results with less code means that we have less room for error. We, as programmers, are always inclined to go with the more elegant solution - it's what we were trained to do! This however, does come at a price that we don't usually consider: the human factor.
Here's the problem with choosing S2. When another programmer reads this code, it will take them a moment to decipher it. Whereas S1 follows a natural thought process (If the switch is on, then turn it off. Otherwise, turn it on.) Of course, any competent programmer will see what is happening in S2 within a matter of seconds. But that's not the point. The point is that we should be constantly aware that other people may someday be reading our code. We need to realize that sometimes writing longer code is okay, if it means that the code will communicate better to the person reading it and it won't harm performance.
The competent programmer is fully aware of the limited size of his own skull. He therefore approaches his task with full humility, and avoids clever tricks like the plague.
— Edsger W. Dijkstra
Code,
Programming 






Reader Comments