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
rolf = copter
fnuh = guh
}
PROTIP: This works great with the JEE HttpServletRequest and HttpServletResponse classes.
Removing temporary variables
Conditional blocks in which you access another property of the same object can look like this
if (new File('rofl').exists()) {
assert new File('rofl').length() > 0;
}
or you might be tempted to use a temporary variable
File f = new File('rofl');
if (f.exists()) {
assert f.length() > 0;
}
neither of which conveys that it’s all about the file. Groovy makes this easier and more readable:
new File('rofl').with {
if (exists()) {
assert length() > 0
}
}
Harmonizing API access
By going with with, you can turn any API, wether it’s fluent or setter-based into one simple, easy-to-read style.
