Search

Advertising

Home Blog Game Development Code Better: Booleans instead of Comments
Code Better: Booleans instead of Comments Print E-mail
Written by Markus Ewald   
Wednesday, September 15 2010 11:48

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!

 

Comments  

 
0 #1 Olle HÃ¥kansson 2010-09-26 17:17
That's a really good trick, thanks for sharing!
Quote
 
 
0 #2 Dan 2010-10-07 20:45
I prefer the following for that last if-statement:

return (isInsideHeight Field)? heightField[x,y ] : 0.0f;
Quote
 
 
0 #3 Cygon 2010-10-13 21:21
Good idea!

Using the ternary operator in this case really helps readability :)

I tend to ignore it because in some cases, it can huge the fact that a condition is being checked, but this is clearly not one of those cases.
Quote
 

Add comment


Security code
Refresh



Joomla Template by Joomlashack