Groovy Bar & Grill

September 14, 2006

Groovy Category Example

Filed under: Groovy Grill — jawild59 @ 9:43 pm

I cut my Java teeth on an old edition of Java Examples in a Nutshell. I thought it might be a good exercise to translate some of the Java code to Groovy. By the second example in the book I realized I was right. The example prints out every number from 1 to 100, except that if the number the number is divisible by 5 it prints “fizz,” if it is divisible by 7 it prints “buzz,” and if it is divisible by both 5 and 7 it prints “fizzbuzz.”

Like most examples in the book, the Java code is not exactly exemplary, as evidenced here:

public class FizzBuzz {
    
    public static void main(String[] args) {
        for (int i = 1; i <= 100; i++) {
            if (((i % 5== 0&& ((i % 7== 0))
                System.out.print("fizzbuzz");
            else if ((i % 5== 0)
                System.out.print("fizz");
            else if ((i % 7== 0)
                System.out.print("buzz");
            else
                System.out.print(i);
        System.out.print(" ");
    }
}

I like self-documenting code so rather than use comments to explain the logic, I try to write code that is readable by non-programmers. Using a Groovy Category to add a method to an existing Java class makes that job easier. Since the Category examples on the Groovy site are not very intuitive, I thought I’d share an example here:

use (Multiplicity.class) {
  range = 1..100
  range.each {number ->
    if (number.isMultipleOf(5&& number.isMultipleOf(7)) {
      print "fizzbuzz"
    else if (number.isMultipleOf(5)) {
      print "fizz"
    else if (number.isMultipleOf(7)) {
      print "buzz"
    else {
      print "${number}"
    }
    print " "
  }
}
  
class Multiplicity {
  static boolean isMultipleOf(Integer dividend, Integer divisor) {
    dividend % divisor == 0
  }
}

This is what I like about Groovy. Not only is there less code (fewer keystrokes) but (and maybe more importantly) there is less to read in order to grasp the logic.

No Comments Yet »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.