mobile menu icon

Improve your reds

Published by Daniel Ojeda & Manuel Rivero on 08/06/2018

TDD, Testing

Improving your reds is a simple tip that is described by Steve Freeman and Nat Pryce in their wonderful book Growing Object-Oriented Software, Guided by Tests.

It consists in a small variation to the TDD cycle in which you watch the error message of your failing test and ask yourself if the information it gives you would make it easier to diagnose the origin of the problem in case this error appears as a regression in the future. If the answer is no, you improve the error message before going on to make the test pass.

Variation to TDD cycle: feedback on diagnostics
From Growing Object-Oriented Software by Nat Pryce and Steve Freeman.

Investing time in improving your reds will prove very useful for your colleagues and yourself because the clearer the error message, the better the context to fix the regression error effectively. Most of the times, applying this small variation to the TDD cycle only requires a small effort.

As a simple example, have a look at the following assertion and how it fails

assertThat(new Fraction(1,2).add(1), is(new Fraction(3,2)));
Expected: is <Fraction@2d8e8c3a>
     but: was <Fraction@2d8e84b8>

Why is it failing? Will this error message help us know what’s happening if we see it in the future?

The answer is clearly no, but with little effort, we can add a bit of code to make the error message clearer (implementing the toString() method).

public String toString() {
  return "Fraction{" +
    "numerator=" + numerator +
    ", denominator=" + denominator +
Expected: is <Fraction{numerator=3, denominator=2}>
     but: was <Fraction{numerator=1, denominator=2}>

This error message is much clearer that the previous one and will help us to be more effective both while test-driving the code and if/when a regression error happens in the future, and we got this just by adding an implementation of toString() generated by our IDE.

Take that low hanging fruit. Start improving your reds!

Originally published in Manuel Rivero's blog.

Volver a posts