Java Reference
In-Depth Information
Thenextlisting showsaJavainterface, called UtilityMethods ,containing three meth-
od declarations.
Listing 6.1. A Java interface with three methods
public interface UtilityMethods {
int[] getPositives(int... values);
boolean isPrime(int x);
boolean isPalindrome(String s);
}
In true test-driven development (TDD) I would now write the tests, watch them fail, and
thenwritethecorrectimplementations.Becausethesubjectofthischapteristhetestsrather
than the implementations, let me present the implementations first. [ 2 ]
2 I try to use TDD, but more often I use GDD, which stands for Guilt-Driven Development. If I write code and it's
not tested, I feel guilty and write a test for it.
The following listing is the Java implementation of the UtilityMethods interface.
Listing 6.2. The Java implementation of the UtilityMethods interface
import java.util.ArrayList;
import java.util.List;
public class JavaUtilityMethods implements UtilityMethods {
public int[] getPositives(int... values) {
List<Integer> results = new ArrayList<Integer>();
for (Integer i : values) {
if (i > 0) results.add(i);
}
int[] answer = new int[results.size()];
for (int i = 0; i < results.size(); i++) {
answer[i] = results.get(i);
}
return answer;
}
public boolean isPrime(int x) {
if (x < 0) throw new IllegalArgumentException("argument must be > 0");
if (x == 2) return true;
for (int i = 2; i < Math.sqrt(x) + 1; i++) {
if (x % i == 0) return false;
 
Search WWH ::




Custom Search