Using booleans to document code

Today I want to share a tip on how to write self-documenting code that I picked up from the book Code Complete 2 by Steve McConnell. I will do this be showing you some code I just wrote, but let us start with the actual tip.

Instead of merely testing a boolean expression, you can assign the expression to a variable that makes the implication of the test unmistakable.

The following code was my first try, not employing the tip.

void CETabWidget::wheelEvent(QWheelEvent *e)
{
  QTabBar *tabs = tabBar();
  if (e->y() < tabs->y() || e->y() > (tabs->y() + tabs.height())) {
    e->ignore();
    return;
  }
 
  // handle wheel event
}

Even though I wrote the code myself, I have problems understanding it. And making sure it’s correct takes more than a quick glance. If you want to understand this code in six months, you have to add a comment. So let us take a look at the same code rewritten to use two extra booleans.

void CETabWidget::wheelEvent(QWheelEvent *e)
{
  QTabBar *tabs = tabBar();
  const bool cursorAboveTabBar = (e->y() < tabs->y());
  const bool cursorBelowTabBar = (e->y() > (tabs->y() + tabs->height()));
  if (cursorAboveTabBar || cursorBelowTabBar) {
    e->ignore();
    return;
  }
 
  // handle wheel event
}

Now you can quickly figure out that the wheel event is only handled if the cursor is inside the tabBar. And it’s actually possible to take a quick look and be sure that the code is doing what it’s supposed to.

Of course, for this to be of any good, you need to give the boolean variables meaningful names. Naming them a and b wouldn’t help a bit.

The best thing with this approach? You don’t have to write comments and still get code that people can understand. Ah, the joy!

Posted Sunday, April 9th, 2006 under programming.

Tags: , ,

Comments are closed.