Coding

Amazing substring behaviour

In a recent code review at my workplace I found a piece of C# code that contained something along this line:

string foo = "bar";
string substring = foo.Substring(3);

Clearly index position 3 is beyond the end of the string, so I thought I had found a bug and was about to flag the code. Then it occurred to me: Why had the unit tests not failed during the gated checkin build?

The Art of Computer Programming

Here's a line of code that I recently sighted when I had to dig through ancient Excel VBA cruft at work:

Falsch = True

For German speakers: The code works because it uses a non-keyword (Falsch) as the variable name. For non-German speakers: "falsch" is German for "false", so the original code can be translated to:

False = True

After a moment of disbelief, I couldn't help but admire the amount of badness that is compressed into this single line of code - there is even a philosophical statement here! It's so fabulous that I consider it to be a real piece of computer programming art!

Implementing Binary Search

This afternoon, I was reading a chapter in "Beautiful Code" (check it out at Amazon). There was a reference to the binary search algorithm presented in Jon Bentley's book "Programming Pearls" (see Amazon), accompanied by the challenge to write a correct implementation of the algorithm. To quote from Bentley:

Most programmers think that with the above description [of the algorithm] in hand, writing the code is easy. They are wrong. The only way to believe this is by putting down this column right now and writing the code yourself. Try it.

I tried it.