Method
This was only my second time using Eclipse, and first I had to remember to create a new Java Project and package. Otherwise, using Eclipse was pretty straightforward, and its syntax highlighting, checking and suggestions even made things easier. I had been introduced to unit testing in my ICS 413 class, so I created a JUnit test case to check the results of my FizzBuzz.getResult() method. However, I had never worked with JUnit before, and I couldn't recall the syntax that was presented in class, so I turned to Google and searched for a quick primer on JUnit. I managed to come up with the following code:
FizzBuzz.java
package ics413package;
public class FizzBuzz {
public static String getResult (int num){
if ((num%3==0)&&(num%5==0)){
return "FizzBuzz";
}
else if (num%3==0) {
return "Fizz";
}
else if (num%5==0) {
return "Buzz";
}
else {
return ((Integer)num).toString();
}
}
public static void main (String[] args) {
for (int i=1; i<=100; i++) {
System.out.println(getResult(i));
}
}
}
TestFizzBuzz.java
package ics413package;
import junit.framework.TestCase;
public class TestFizzBuzz extends TestCase {
public void testResult() {
assertEquals("Testing 1", "1", FizzBuzz.getResult(1));
assertEquals("Testing 3", "Fizz", FizzBuzz.getResult(3));
assertEquals("Testing 5", "Buzz", FizzBuzz.getResult(5));
assertEquals("Testing 15", "FizzBuzz", FizzBuzz.getResult(15));
}
}
My code is slightly different from what was demonstrated in class, but it works. This whole process took me about 15 minutes.
Looking over my code now, I realize that using String.valueOf() or Integer.toString() in my FizzBuzz.getResult() method would probably have been more efficient and cleaner than casting to an Integer wrapper object and using toString(), but I didn't think of it at the time.
Conclusions
I am now a bit more familiar with Eclipse and JUnit. The test-driven development process is an interesting approach. My initial instinct was to attack the problem directly by writing a program that loops through the numbers, checks the modulo conditions, and prints out the corresponding results. This exercise has shown me that, rather than tackling the problem as a whole, the task can be broken down into test cases and addressed from that perspective; it is sort of a bottom-up approach. The advantages are that complex problems are broken down into simpler test cases which are more easily solved; and the resulting code does exactly what it is supposed to do.
I still have some reservations about test-driven development, however. First, it is not always easy to identify and test all the relevant and interesting cases that might "break" your code. Second, from the very little that I know of test-driven development, it seems like a patchwork process where one addresses issues as they come up, and that seems counterproductive to overall coherence (although I bet that in the coming weeks I will look back at this sentence and see how ridiculous it was).
No comments:
Post a Comment