Tuesday, January 31, 2012

TDD with JUnit - Implementation

Let us now implement Calculator.java, so it does the addition.

First we do the obvious, and return the sum of the two numbers.
Like this:
 package org.confucius;  

public class Calculator implements BasicCalculator{

public int add(int a, int b) throws Exception {
return a + b;
}
}



If you run the Junit tests, the first two tests will pass and the third (huge values) will fail.

So we update our Calculator implementation, to use BigDecimal.
Like this:
 package org.confucius;  

import java.math.BigDecimal;

public class Calculator implements BasicCalculator{

public int add(int a, int b) throws Exception {
BigDecimal A = new BigDecimal(a);
BigDecimal B = new BigDecimal(b);
BigDecimal biggestInt = new BigDecimal(Integer.MAX_VALUE);

BigDecimal SUM = A.add(B);

if (SUM.compareTo(biggestInt) == 1)
throw new Exception();
else
return a + b;
}
}



Now if you run the JUnit tests, all 3 of them will pass.

Is this the best implementation of Calculator?

If there were more tests in the suite, maybe it would have broken. We would have then had to figure out a different implementation.

Or maybe in a few months someone will have a better idea than using BigDecimal. Something which runs faster. The code can be refactored at that point too.

Either way, TDD will ensure the integrity of our code.

No comments: