Sunday, September 5, 2010

Groovy Categories for temporary mixins

In my previous post I showed how you could add the Apache StringUtils capability into the standard String class in BootStrap.groovy for the entire application to use.

But what if for some reason you do not have access to BootStrap.groovy or adding this kind of mixin for everyone is a little egregious.

This is where Groovy Categories come in very handy. A Groovy 'Category' can be added to any class at runtime by using the 'use' Groovy keyword.

Below is a simple unit test which shows how this is done very easly.

Lines 2-6 show the typical Java usage( with a little Groovy thrown in) using StringUtils.

Lines 9 - 13 so the how the 'use' keyword can be used to temporarily mixin the StringUtils capabilities to a String.


1:    void testUseCategory() {  
2: String testString = "break.this.string.up.into.words"
3: println "Test StringUtils.split"
4: StringUtils.split(testString, ".").each {
5: println it
6: }
7:
8: println "Test use(StringUtils)"
9: use(StringUtils) {
10: testString.split(".").each {
11: println it
12: }
13: }
14: }
15:


This example shows how to take a third party library and mix it in, but you can also do this for your own utility classes. You could create a utility class that operates on your class, and then 'use' that utility class to mix those methods in as though they exist on your class. This helps to keep your class focused on the business problem and makes the class much easier to read.

Just another example of some really cool Groovy capability.

I don't always code - but when I do, I prefer Groovy.