Fizz Buzz Kata

Fizz Buzz Kata

Requirement

Write a function that takes numbers from 1 to 100 and outputs them as a string, but for multiples of 3, it returns Fizz instead of the number, and for multiples of 5, it returns Buzz. For numbers that are multiples of both 3 and 5, it returns FizzBuzz.

Kata approach

Step 1

Let's first pick the behavior where numbers not divisible by 3 or 5 are returned as a string. Let's start with number 1.

Write a new failing test.

When we fizzbuzz number 1, we get back a string representing it

Use fake as an implementation strategy.

return "1";

Run the test and make sure it's green.

Step 2

Write a new failing test since we do not have enough examples to prove the behavior we are implementing yet.

When I fizzbuzz number 2, I get back a string representing it

Use obvious implementation

if (number == 1) 
    return "1";
else 
    return "2";

Run the tests and make sure they are all green.

Step 3

Write a new failing test.

When I fizzbuzz number 4, I get back a string representing it

Why did we not write the test for number 3 after the test for number 2?

The reason is that number 3 would add new behavior to the code base, and we haven't finished implementing the behavior we are working on yet.

Use obvious implementation

if (number == 1 )
    return "1";
else if (number == 2 )
    return "2";
else return "4";

Run the tests and make sure they are all green.

Step 4

We now have duplication in our code, so it is time to refactor to remove it.

return str(number);

After the refactor, run the tests and make sure they are all green.

Step 5

Now that we have tests to prove the behavior for numbers not divisible by 3 or 5, we can start testing numbers divisible by 3.

Write a new failing test.

When I fizzbuzz number 3, I get back "fizz"

Use obvious implementation

if (number == 3 )
    return "fizz";
else 
    return number.ToString();

Run the tests and make sure they are all green.

Exercise: continue the kata similarly

Take over from this point on and finish the Fizz Buzz kata on your own. You could use this repo which has the partial solution to the kata (until Step 5) and save time!

Last updated