After only a couple of weeks of Judo practice, my son got bored. He complained that he wasn’t learning anything, because he kept doing the same thing over and over.
It’s not just young children that confuse learning and doing new things. For instance, how many software developers go through the trouble of deliberate practice by performing katas or attending dojos?
It may seem silly to repeat exercises that you’ve already done many times, but it’s not. It’s the only way to become a black belt in your field. And remember that mastery is one of the three intrinsic motivators (the others being autonomy and purpose).
Practicing means slowing down and moving focus from outcome to process. It’s best to use simple exercises that you can complete in a limited amount of time, so you can do the same exercise multiple times.
I’ve found that I virtually always learn something new when I practice. That’s not because I’ve forgotten how to solve the problem since last time, but because I’ve learned new things since then and thus see the world through new eyes.
For example, since Java 8 came out I’ve been trying to use the new stream classes to help move to a more functional style of programming. This has changed the way I look at old problems, like FizzBuzz.
Let’s see this in action. Of course, I start by adding a test:
This test uses the When…Should form of unit testing that helps focus on behavior rather than implementation details. I let Eclipse generate the code required to make this compile:
The simplest code that makes the test pass is to fake it:
Now that the test passes, it’s time for refactoring. I remove duplication from the test:
Next I add a test to force the real implementation:
OK, now let’s get real with a test for Fizz:
Similar for Buzz:
Here I just copied and pasted the
if statement to get it working quickly. We shouldn’t stop there, of course, but get rid of the dirty stuff. In this case, that’s duplication.
First, let’s update the code to make the duplication more apparent:
I just created a new value object to hold the two values that I had to change after the copy/paste.
Now that the duplication is clearer, it’s easy to remove:
I’m not done cleaning up, however. The current code suffers from feature envy, which I resolve by moving behavior into the value object:
Now that I’m done refactoring, I can continue with multiples:
The final test is for simultaneous “Fizz” and “Buzz”:
This code is rather complex, but this is where streams come to the rescue:
Note how the
if statements disappear. Rather than spelling out how something needs to be done, we say what we want to achieve.
We can apply the same trick to get rid of the remaining
if statement in our ode base:
The code is on GitHub.