Codementor Events

Why I Like Groovy

Published Jun 08, 2017

Java can have so much boilerplate. Here is a small sample:

public interface PreferenceMatcher {
    boolean matches(Product product);
}

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;
    }

}

And the equivalent in Groovy:

class CopyMatcher {

    def triggerWord

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

}

Groovy has a powerful default constructor that understands the fields of a class. And it uses duck typing so I don't have to repeat words for each variable.

Discover and read more posts from Jean Tessier
get started
post commentsBe the first to share your opinion
Show more replies