Practical Uses For Fizzbuzz – Part 2

Wasn’t it your own Hartley who said, nothing reveals humanity so well as the games it plays? Almost right. Actually, you reveal yourselves best in how you play.
– Q to Riker, “Hide and Q”
Star Trek: The Next Generation

How someone writes code can tell you a lot about them.

Fizzbuzz, although simple, provides plenty of fodder for discussion, and in that discussion can show you whether or not a programmer has the chops to produce quality code.

Fizzbuzz can be used to validate resume buzzwords.  If someone declares themself as an ‘Expert’ in C#, it’s really easy to see if they really are. I mean, an Expert should know the modulus operator, right?

Take this example:

 

for (i = 1, i <= 100, i++) 
{      
    if (i mod 5 == 0 && i mod 3 == 0) 
        print “fizzBuzz”;     
    else if (i mod 5 == 0)
        print “buzz”;
    else if (i mod 3 == 0)
        print “fizz”; }
}

There are a few good starting points to be made from this piece of code: 1. What is the modulus operator in your favorite languge? 2. Where’s the bug? 3. How can we improve this code to reduce duplication?

If the candiate believes that the modulus operator for their favorite language is mod, and they aren’t in Visual Basic, then the interview should be terminated. There’s no sense in going past that point.

While there isn’t a bug in this code per se, it could use some refactoring; the logic is left wanting, to put it simply. The order of operations is opposite of what you’d expect.  3 comes before 5, and in any loop 3 will always come before 5. This isn’t a bug, but it is a logical error, and fixing logical errors are central to debugging harder problems.  If your maintanence programmer has to figure out why you did something counter intuitively, it heightens the chance that he’s going to make a mistake.

Finally, the code can be improved substantially by using a string variable and appending each part to it.  If a candidate has gotten past the first gate and into the second, this question will help shape your mind on what sort of programmer they are.

Example ‘fixed’ code:

for (int i = 1; i <= 100; i++)
{
    string output = String.Empty;
    if (i % 3 == 0)
        output += “fizz”;
    if (i % 5 == 0)
        output += “buzz”;
    if (output == String.Empty)
        output = i.ToString();
    Console.WriteLine(output);
}

It doesn’t have to be a complex code sample to be of use in an interview, but it does have to be done on the spot. Using a code sample is the only way to really see what sort of code the programmer turns out.

Don’t neglect this tool when interviewing programmers, or your bottom line will regret it.

Leave a Reply