A more realistic example of refactoring in TDD

Image for post
Image for post
A magenta triangle in the complex plane. Its vertices are on 0 (the black dot) and 7 and 7i, both of which are cyan dots.

The example: a function to create ranges of Gaussian integers

Writing the stub

    // STUB TO FAIL THE FIRST TEST
public List<GaussianInteger> to(GaussianInteger endPoint) {
List<GaussianInteger> range = new ArrayList<>();
range.add(new GaussianInteger(0, 0));
return range;
}

Writing the tests

Getting a couple of the tests to pass

    public List<GaussianInteger> to(GaussianInteger endPoint) {
List<GaussianInteger> range = new ArrayList<>();
if (this.equals(endPoint)) {
range.add(this);
return range;
}
if (this.real == endPoint.real) {
range.add(this);
GaussianInteger inBetweener = this;
GaussianInteger incr = new GaussianInteger(0, 1);
if (this.imag > endPoint.imag) {
incr = incr.times(-1);
}
do {
inBetweener = inBetweener.plus(incr);
range.add(inBetweener);
} while (!inBetweener.equals(endPoint));
return range;
}
if (this.imag == endPoint.imag) {
range.add(this);
GaussianInteger inBetweener = this;
int incr = 1;
if (this.real > endPoint.real) {
incr = -1;
}
do {
inBetweener = inBetweener.plus(incr);
range.add(inBetweener);
} while (!inBetweener.equals(endPoint));
return range;
}
range.add(this);
// TODO: Logic to pass diagonal test
return range;
}

Some more refactoring almost skipped over

    public List<GaussianInteger> to(GaussianInteger endPoint) {
List<GaussianInteger> range = new ArrayList<>();
range.add(this);
if (this.equals(endPoint)) {
return range;
}
GaussianInteger step;
if (this.real == endPoint.real) {
step = new GaussianInteger(0, 1);
if (this.imag > endPoint.imag) {
step = step.times(-1);
}
} else if (this.imag == endPoint.imag) {
step = new GaussianInteger(1, 0);
if (this.real > endPoint.real) {
step = step.times(-1);
}
} else {
step = endPoint.minus(this);
boolean keepGoing = true;
int divisor = 2;
while (keepGoing) {
try {
step = step.divides(divisor);
keepGoing = step.abs() > 1.0;
divisor = 1;
} catch (NotDivisibleException nde) {
keepGoing = nde.getAbs() > 1.0;
}
divisor++;
}
}
GaussianInteger inBetweener = this;
do {
inBetweener = inBetweener.plus(step);
range.add(inBetweener);
} while (!inBetweener.equals(endPoint));
return range;
}

is a composer and photographer from Detroit, Michigan. He has been working on a Java program to display certain mathematical diagrams.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store