Saturday, October 4, 2008

Sometimes you're still wrong...

It seems funny how sometimes you can just know you're right, and still be proven wrong. Take for example this old programming idiom.

if(condition == true) {
return true;
else {
return false;

Everyone should recognize this by the time they've completed a CS (or equivalent) degree. There are two things wrong with the above code. First, if the condition variable is boolean, then there's no need to compare it to true. Second, the whole idiom simplifies down to just

    return condition;

There, we've just saved five lines. I've corrected this so many times I've lost count. Then what's my point, you ask? When is the six line version really okay? When you're debugging. Sometimes you want to set a break point where the condition is either true or false. If you only have the return statement to set the break point on, the debugger stops every time it hits that one line. That's really annoying if the condition you're interested in only happens once in a thousand evaluations.

So what's the real lesson here? Even when you know you're right, even when you've been right for years, you can still be wrong.


Jon Skeet said...

Any reason not to set the breakpoint on the return line but make it conditional? That's certainly what I'd do in Eclipse - which IDE do you use?

Conditional breakpoints are heavier than unconditional ones in terms of performance, but I'd rather that than morph my code out of shape :)

Locivars Vonvik said...

And you are definitely STILL WRONG! Conditional breakpoints are what you need... I totally agree with Jon.

Bill the Lizard said...

You're both right, conditional breakpoints are better in this case if you have them. I don't worry about them being "heavier" because it doesn't matter how slow your code runs in the debugger.

Bill the Lizard said...

By the way Jon, I use NetBeans, so I definitely should be using conditional breakpoints. Also, I love your blog.

locivars, am I "STILL WRONG", or was I right all along? :)