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 { |
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) { |
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.