May 2012
1 post
6 tags
Groovy annotations: @TupleConstructor
If you use an inversion-of-control/dependency injection container like PicoContainer that favors constructor injection, you might have classes that look like this:
class Foo {
Guh guh
Keks keks
Blorb blorb
Foo(Guh guh, Keks keks, Blorb blorb) {
this.guh = guh
this.keks = keks
this.blorb = blorb
}
}
Notice the constructor only sets fields? Why should you have to write this glue...
February 2012
1 post
9 tags
Copy Properties or how to Clone a Class to a...
René has asked me how to copy properties/fields of an instance of one class to an instance of another class. I.e. you have
class A {
int a
}
and
class B {
int a
}
where B obviously does not extend A. You want to copy all properties of an instance of A to an instance of B.
Copy Properties
The solution is to access the properties property of A, filter it to remove the class and metaClass...
January 2012
1 post
6 tags
Groovy programming with... with
The with method, which is added to all objects by Groovy, “allows the closure to be called for the object reference self.”
This sounds a bit complicated so here are some easy use cases for with:
Setting fields
Many APIs force you to do endless obj.setSomething(something) calls. In Groovy, …
keks.setFoo(someFoo);
keks.setRolf(copter);
keks.setFnuh(guh);
… becomes…
keks.with {
foo = someFoo
...
October 2011
1 post
15 tags
Cleaner logging with Log4j, Commons Logging and...
Logging frameworks are the Java programmer’s finger exercise — think content management systems for PHP programmers.
Most libraries these days use either Log4j or commons-logging, which is fine because SLF4J can replace commons-logging and redirect output from classes using either API to Log4j.
Problems only arise when the odd library uses the java.util.logging log framework. Not...
August 2011
1 post
5 tags
CodeNarc for Eclipse released
My friend René has released CodeNarc for Eclipse which integrates CodeNarc into Eclipse.
CodeNarc tries to find errors and potential problems in Groovy code. The list of code checks is already quite large and covers a lot more than the basics (for example bitwise OR instead of boolean OR).
If you find yourself writing more Groovy and less Java, it might make sense to expand static analysis to...
June 2011
1 post
7 tags
Groovy operators: The spread operator is null-safe
Groovy’s spread operator lets you collect a property of objects from a collection. Here’s an example:
[ 1, 2, 3 ]*.toString() == [ '1', '2', '3' ]
This is identical but shorter than calling
[ 1, 2, 3 ].collect { it.toString() }
Keep in mind that, just like .collect, the spread operator is null-safe, i.E. both of these work without throwing any exceptions:
null*.toString()
[ 1, null,...
May 2011
1 post
7 tags
February 2011
1 post
8 tags
Java hangs when converting 2.2250738585072012e-308...
The big news now is that
Java — both its runtime and compiler — go into an infinite loop when converting the decimal number 2.2250738585072012e-308 to double-precision binary floating-point.
This has a big impact on web applications since many of them use the java.lang.Double#parseDouble(String) method with data input by the user.
While I’m sure most programmers are aware of SQL injection,...
August 2010
1 post
6 tags
Count Words in Groovy
This is a little snippet to show you how to get the word count of a text in Groovy.
def text = '''
right about now, the funk soul brother.
check it out now, the funk soul brother.
'''
int words = text
.collect { it.charAt(0).digit || it.charAt(0).letter ? it : ' ' }
.join('').tokenize(' ').size()
June 2010
1 post
12 tags
Long number arithmetic problematic in Groovy
When you divide long numbers in Groovy, you are calling a recursive algorithm that only terminates once an Exception is thrown (org.codehaus.groovy.runtime.typehandling.BigDecimalMath#normalize(BigDecimal)).
This is not a good thing because with Groovy’s inflated call stacks, it means that, for every long division, the entire stack is cloned. And that’s costing CPU cycles and...
May 2010
3 posts
6 tags
Groovy creates BigDecimal numbers deliberately. […] 3.5 is a BigDecimal,...
– Comment by Guillaume Laforge on JVM Language developpers: Your house is burning.
8 tags
foo.class or foo.getClass()? Which one to use?
Groovy converts calls to foo.x to foo.getX() – that’s common perception.
Now, you might be tempted to write foo.class to access the object’s class.
But when you do that, sometimes null is returned, depending on how much Groovy and Java there is in your project.
The reason
For Groovy objects – which is any class generated from a file with a .groovy extension –, foo.class will be mapped to...
8 tags
Three good reasons for Groovy
It’s easy to learn
If you know Java, you know Groovy. You start by getting rid of boilerplate code such as casts, getters and setters and the public keyword. And semicolons. Then, you replace tedious loops with any, each, find and findAll. Groovy’s operators and metaprogramming might come next.
Wide syntactic range
A while ago, I converted a Ruby script to Groovy and, while the Groovy...
April 2010
8 posts
8 tags
as Groovy as it can go!
“as” is one of the wonderful little things in Groovy.
Instead of boring you with what it is, I searched my workspace for my uses of “as” and let the examples talk instead.
Closures and as as a Replacement for Anonymous Inner Classes
def nullIOFileFilter = { true } as IOFileFilter
What it does: Creates a Proxy that implements IOFileFilter (from commons-io) with every method call on the proxy...
11 tags
Extend any class with Groovy's categories
Groovy’s category system lets you add new methods to any class. And that’s more fun than you would think.
Using categories combines a static method that takes an instance of the class as its first parameter and any number of additional parameters, the use keyword and a closure:
class Foo {
static Bar rofl(Keks k) {
k.doIncredibleThings()
}
}
Keks keks = createKeks()
use (Foo) {
...
7 tags
Simple mapping with Groovy: ISO-639
One thing I’m sure every programmer hates writing is mapping code – code that converts from one format to another.
Glue code might come in second place. ;-)
In this post, I’ll show you how to make writing mapping code easier and faster with Groovy. We’ll write an ISO-639 converter in Groovy as an example of mapping – on one hand are English language names (such as...
5 tags
Groovy's in operator
Groovy’s in operator roughly corresponds to Java’s instanceof operator. Like its Java counterpart, in lets you check if an object is of a certain type.
if (foo in Keks) doIt()
Unfortunately, you cannot shorten usage of the in operator by combining multiple types in a list, like this example:
if (foo in [ Keks, Blorb, Rolf ]) doIt()
However, by using Groovy’s find method, we can...
7 tags
Default arguments in Groovy
Groovy supports default arguments (otherwise known as optional parameters) in constructors and methods. This reduces boilerplate code.
Example Constructor Optional Parameter
class Keks {
Blorb blorb
Keks(Blorb blorb = null) {
this.blorb = blorb
}
}
This lets you construct instances of Keks by typing
Keks keks = new Keks()
as well as
Keks keks = new Keks(someBlorb)
Note that...
5 tags
Useful Groovy Operators
Groovy adds a number of interesting operators that make some things that are tedious to do in Java very easy.
The Elvis ?: Operator
The Elvis operator is a compact way to express defaults in case an expression evaluates to false.
cache[name] = obj ?: NULL
This adds obj with a key of name to cache, substituting an Object called NULL if obj evaluates to false.
In Java, the code is less...
9 tags
Dynamic Proxies with Metaprogramming
Groovy’s metaprogramming features are wonderful.
In this example, we combine Groovy’s as automatic Proxy conversion with metaprogramming to create a simple stub for an interface.
Automatic Proxies
Two ways in Groovy to create an implementation of an interface at runtime are: One based on Closures and one based on Maps.
The Closure version usually looks like this
{ it ->...
4 tags
Welcome to Groovy Programming
Welcome to groovy-programming.com.
I have been programming Java for 8 years and have begun writing Groovy a year ago. Programming Groovy has made me more productive and has been fun, too.
This blog will cover all kinds of tips and tricks about Groovy. I invite you to try out Groovy, subscribe to this blog and learn something new.
Other Groovy blogs you might want to subscribe to:
Messages from...