Code Better: Booleans instead of Comments

There are lots of small tricks a programmer learns over time. With this post, I’m starting a little column called Code Better in which I’ll share some of my own tricks! If you want to show off some useful tricks of your own, I’d be happy to publish them here, too :)

The first trick is a simple technique to make complicated if statements more readable. Let’s take a look at this beast:

// Only access the height field if the position is within
if(
  (x >= 0) && (y >= 0) &&
  (x < this.heightField.Width) &&
  (y < this.heightField.Length)
) {
  return this.heightField[x, y];
} else { // Position is outside the height field
  return 0.0f;
}

The code isn’t unreadable per se, but it takes more than a glance to understand what’s going on. The comments help, but there’s a more elegant way that makes those comments entirely redundant:

bool isInsideHeightField =
  (x >= 0) &&
  (y >= 0) &&
  (x < this.heightField.Width) &&
  (y < this.heightField.Length);

if(isInsideHeightField) {
  return this.heightField[x, y];
} else {
  return 0.0f;
}

The beauty in this is that the first thing you see is bool isInsideHeightField, prominently positioned at one indent less than the conditions. Your brain registers the purpose of that block of code before it encounters the actual code.

The if below is also much more obvious. If the position is inside the height field, look up the value in the height field, otherwise return zero. Almost like reading english.

Finally, this level of obviousness eliminates the need for any additional comments in the code!