HappyBunny":342ct2dv said:
When I read further and saw that it was 90% had at least 1 bug and they weren't able to do any testing (except walking through it by hand), that's much less interesting.
That's what I thought at first, but as I've thought about it more, I tend to disagree with this view. Being able to go over your code by hand and reason about what it does is an important skill, because it gives you a different view of your code than testing or debugging does. When you step over it by hand,
you are the computer, and the advantage is that you can question why you're doing something and whether it's the correct way to do it during every step. You can also think about boundary conditions on every step and whether they might apply. It can be an opportunity to catch bugs you might not catch during testing or even step-through debugging.
For example, at one point when I was writing the algorithm, I included the midpoint again in the next call. This is unnecessary -- we just established that our key was either less than or greater than the midpoint, so the midpoint should be excluded -- and it results in several extra comparisons. It might also produce the wrong result -- I'm not sure because I never got to that point. As I walked through the code by hand, I stopped to ask myself "Why am I doing so many comparisons? This doesn't feel like a binary search" and then I found the error.
If it had produced the correct result (and I'm not sure it would have), I might have not found the bug at all and declared it correct.
Then there's this:
Code:
int mid = (low + high) / 2;
It took years for this bug to be flushed out by testing, but it really should have been found in just a few minutes of thinking about the code. The problem is that it was proven correct and published, and once this happens, too few people ever think to question it or check it for bugs. But you're adding two integers together -- the possibility for overflow always exists in that case, and you should always ask whether it's possible for x + y to be greater than the max value for the data type (the same applies for multiplication, and for subtraction or division when one term can be negative). The overflow condition is easier to see while you're writing it -- if you're trained to look for it -- than it is to find during testing. You
might catch the bug above during testing if you thought to construct a test case for it, but it would be better to write it in a way that never produces overflow under any condition. And this does require the skill of thinking about your code and getting certain things right before you even test them.
I can't say I felt this way a week ago, but after this thread and another with similar content, I realize how important it is to parse through code and verify its correctness rather than assuming we'll find everything during debugging.