As long as they are progressing towards the goal steadily, everything is good. Somebody might write the right code straight within a minute. Someone else might take more time in explaining his thinking, in factoring the code and in writing tests.
The end goal and time is not important. The important thing is the way to the goal.
For me it took just now some 10-15 minutes using TDD, the same way and quality that I would write production code. If I had written it just off the top of my head, it would maybe have taken one or two minutes (as I see other senior programmers have done it that quickly), but that would have been unprofessional. I wouldn't want to hire somebody who just hacks some code together.
That 10-15 min was about as fast as I could type, except at a couple of points where I was thinking about descriptive method names and afterwards I did some refactoring to make the code more expressive. I considered the alternative of concatenating "Fizz" and "Buzz", so that there would be one if
less, but that made code less clean to me (maybe because of the mutable state), so I settled with the code below.
public class FizzBuzz {
private static final int FIZZ = 3;
private static final int BUZZ = 5;
public static String textForNumber(int n) {
if (multipleOf(FIZZ * BUZZ, n)) {
return "FizzBuzz";
}
if (multipleOf(FIZZ, n)) {
return "Fizz";
}
if (multipleOf(BUZZ, n)) {
return "Buzz";
}
return Integer.toString(n);
}
private static boolean multipleOf(int multiplier, int n) {
return n % multiplier == 0;
}
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
System.out.println(textForNumber(i));
}
}
}
import junit.framework.TestCase;
public class FizzBuzzTest extends TestCase {
public void test__Multiples_of_3_print_Fizz() {
assertEquals("Fizz", FizzBuzz.textForNumber(3));
assertEquals("Fizz", FizzBuzz.textForNumber(6));
}
public void test__Multiples_of_5_print_Buzz() {
assertEquals("Buzz", FizzBuzz.textForNumber(5));
assertEquals("Buzz", FizzBuzz.textForNumber(10));
}
public void test__Multiples_of_both_3_and_5_print_FizzBuzz() {
assertEquals("FizzBuzz", FizzBuzz.textForNumber(15));
assertEquals("FizzBuzz", FizzBuzz.textForNumber(30));
}
public void test__All_others_print_the_number() {
assertEquals("1", FizzBuzz.textForNumber(1));
assertEquals("2", FizzBuzz.textForNumber(2));
assertEquals("4", FizzBuzz.textForNumber(4));
}
}