vendredi 3 juin 2016

TDD By Example

I’ve been practicing Test Driven Development for years now. Yet, I haven’t read Kent Beck’s book TDD by Example until these days. And I have to admit I learned useful things!

First, you all know the 3 steps of TDD: red bar, green bar and remove duplication. But I though that it talked about duplication in the production code. Actually, the most common aspect of duplication when you TDD is between your testing code and your production code. For instance, when you write as the first test for a sum function:

assert sum (1, 2) == 3

Then the code:

def sum(a, b):
    return 3

The hardcoded value 3 is a duplication you have to get rid of when having a green bar. It’s nice because you don’t have to write another test to create a triangulation situation (notice that following this logic of triangulation, you could create a test for every different input. That’s stupid).

When I began, I did not understand this idea of the most simple implementation possible that passes the tests. Today, I do it systematically: it allows me to get my first green bar quickly. It’s not that simple because all the code that is called in the test has to be implemented. Now I can give an explanation for this way of doing!

I also learned is that the goal of TDD is not to allow you to write the perfect code during your first sprint (or iteration) though it’s a great too to do so. The test harness allows you to deliver good enough code that will be easy to extend when new features are needed. Most of the time, you do not need an over engineered generic code and it’s OK not to comply at 100% to the Open Closed Principle at first.

Refactoring is a very pleasant activity that can give a lot of satisfaction: you are in the green, you add abstraction, you implement design patterns to show your skills to your colleagues. But it takes time and you’re not payed to show technical mastery. You’re paid to add value, to help your company to gain more profit!

I had this problem lately. Getting into Domain Driven Design, I had a tendency to put the patterns in place everywhere. Sometimes, I may have fall into the over engineering trap… Well, that’s learning!