Following on from my earlier posting: The Perils Of Being A Smarty-Pants!…
While doing the washing up, I spotted a couple of ways of making the code more idiomatically ‘Groovy.’ These just popped into my head. Unbidden, I swear!
Fancy a curry?
def fmt = String.&format.curry("%.3f")
@Override
public String toString() {
"""$m
Weight(Pounds): ${fmt(getWeightPounds())}
Weight(Tons): ${fmt(getWeightTons())}"""
}
Notice the way that I am now no longer having to respecify the printf format…Good Stuff!
Also see how the & operator converts a method to a closure so that it can be passed around…More Good Stuff!
Not sure that it buys much in THIS case, but one could also do:
@Override
public String toString() {
def s = new StringBuilder()
s << "$m" << 'n'
[ 'Pounds', 'Tons' ].each { prop ->
s << / Weight($prop): ${fmt("getWeight$prop"())}/ << 'n'
}
s.toString()
}
Sorry, no free set of stainless-steel steak knives, but there’s also (I find this faintly ridiculous…or at least past the point of diminishing returns in terms of bang for buck for this situation):
@Override
public String toString() {
def prefix = 'getWeight'
def s = new StringBuilder()
s << "$m" << 'n'
this.class.declaredMethods.findAll {method ->
method.name =~ prefix
}.each {
s << / Weight(${it.name - prefix}): ${fmt("$it.name"())}/ << 'n'
}
s.toString()
}
To quote the great philosopher, Homer (Simpson, that is): “Shut up brain, or I’ll stab you with a Q-tip.”
Worth preserving for posterity (read: I need to store this in external memory…my internal RAM has too many bad blocks these days).
