Why I Like Groovy

This page discusses some of the things I like about programming in Groovy.

Less Boilerplate

I am working with this model class, in Java. It stores text information about products in "product copy" structures associated with each product.

public class Product {

    private Iterable<ProductCopy> productCopy;

    public Product(Iterable<ProductCopy> productCopy) {
	this.productCopy = productCopy;
    }

    public Iterable<ProductCopy> getProductCopy() {
	return productCopy;
    }

}
public class ProductCopy {

    private String copy;

    public ProductCopy(String copy) {
	this.copy = copy;
    }

    public String getCopy() {
	return copy;
    }

}

I need to select product copies that contain a given word. I can define a working interface and give it a simple implementation. Code that is boilerplate is in red, essential code is in green.

Java:

public interface PreferenceMatcher {
    boolean matches(Product product);
}
import org.apache.commons.lang.StringUtils

public class CopyMatcher implements PreferenceMatcher {

    private String triggerWord;

    public CopyMatcher(String triggerWord) {
        this.triggerWord = triggerWord;
    }

    public boolean matches(Product product) {
        Iterable<ProductCopy> productCopies = product.getProductCopy();
        boolean matches = false;
        for (ProductCopy productCopy : productCopies) {
            matches = (matches || StringUtils.containsIgnoreCase(productCopy.getCopy(), triggerWord));
        }
        return matches;
    }

}

In Groovy, I don't even need the working interface since it uses duck typing to resolve method calls. There is a lot less boilerplate.

Groovy:

import org.apache.commons.lang.StringUtils

class CopyMatcher {

    def triggerWord

    def matches(product) {
        product.productCopy.any { StringUtils.containsIgnoreCase it.copy, triggerWord }
    }

}