Programming Practice That Might Kill Your Code

I was browsing various programming tutorials and saw the code that was technically okay but had problem with being bit difficult to read. I’m one of those coders who believe that there’s enough room in the hard drive to use bit longer variable names…

I probably wouldn’t have noticed this and wrote about it here, but since it was in a beginner’s tutorial – I believe it’s worth mentioning.

The code looked like this:

switch(event.KeyInput.Key)
{
case KEY_W:
case KEY_S:
…{
……core::vector3df v = node->getPosition();
……v.Y += event.KeyInput.Key == KEY_KEY_W ? 2.0f : -2.0f;
……node->setPosition(v);
…}
…return true;
}

Basically there’s nothing wrong with that code. It will check out whether somebody pressed key W or S down and moves a node according to the button pressed. Technically that code looks alright.

But practically there’s a fatal problem that should be avoided readability shouldn’t suffer.

The same code could probably be written something like this (or various alternatives where no “break” lines would be needed etc.):

switch(event.KeyInput.Key)
{
case KEY_W:
…speed = 2.0f;
…break;
case KEY_S:
…speed = -2.0f;
…break;
}
core::vector3df unitPositionVector = unitNode->getPosition();
unitPositionVector.Y += speed;
unitNode->setPosition(unitPositionVector);
return true;

The point is… in the first example, the line “v.Y += event.KeyInput.Key == KEY_KEY_W ? 2.0f : -2.0f;” isn’t very easy to read. Sure, one can get what it means after pondering a while – but in my opinion code should be easy to read. In terms of efficiency we don’t lose anything even if we don’t put all that stuff in one line (after all – it’s the rendering that usually takes time, not asking input from the player once).

But by simply telling what KEY_S and KEY_W do (they change the speed – and it’s pretty easy to spot in which direction) and by mentioning that the vector is moving an unit (or whatever) instead of “v” we can get a better picture pretty fast.

If one must decide between “making code as short as possible” compared to “making readable and easily understandable code”, the latter wins in my books in a heartbeat. Don’t let readability suffer – it may kill your code.

One thought on “Programming Practice That Might Kill Your Code

  1. […] Juuso – Game Producer wrote a fantastic post today on “Programming Practice That Might Kill Your Code”Here’s ONLY a quick extractI was browsing various programming tutorials and saw the code that was technically okay but had problem with being bit difficult to read. I’m one of those coders who believe that there’s enough room in the hard drive to use bit longer … […]