Monday, October 13, 2008

Simply Groovy (How to gain Competitive Advantage on Weiqi Gao's Friday Java Quiz)

Weiqi Gao runs the popular Friday Java Quiz. He provides puzzles and invites us to ruminate on bed-time reading of the Java Language Specification, or to recall a Java Puzzler that may have been discussed over dinner. (He would be dismayed if he knew that we occasionally just watch TV.) Often, he absolutely forbids us from using the compiler.

Whatever: if you're like me, you take your best, thoughtful guess and then fire up an editor to check. Often, this is rushed, because it would be nice to be the first one to post a comment. All too often, I don't get to the verification stage because it is just too much effort. I only have so many public static void mains in me.

These days, I just use Groovy's command-line. It gives me an advantage in terms of speed, and it often makes the problem more fun, because I have to formulate it in a different way.

For example, in the latest quiz, Weiqi says that it can't get much simpler.

In Java, the code is (mostly) as simple as possible:


public class Foo {
public static void main(String[] args) {
Serializable bar = null;
System.out.println(bar instanceof Serializable);

Yet with Groovy's -e parameter, life is much easier (and faster):

$ groovy -e " Serializable bar = null ; \
println (bar instanceof Serializable) "

The snippet above has 2 cool elements: (a) Groovy auto-imports java.util.* and* (e.g. Serializable) for you and (b) it will evaluate an expression on the fly. Because Groovy accepts most Java, this is a handy way to beat the masses to the answer of the Friday Java Quiz.

More than that, it is a great way to answer many quick questions in Java. I often use it in my team's war room when a question arises.

Note: I'm not sure, but I think that -e may have a bug in 1.5+ on a Windows machine. A single statement works fine, but this:

groovy -e " println 'hi' ; println 'there' "

seems to have trouble on a Windows box. Drop a line on your experience.


Michael Easter said...

ps. The Java could be a bit simpler with a static initialization block, but I think Weiqi meant that the puzzle couldn't get much simpler.

Adam said...

"Groovy excepts most Java" or "Groovy accepts most Java"? Seriously, I need to know.
I don't have groovy installed, by this works with Perl on Win32:
C:\Users\Adam>perl -e " print 'hi ' ; print 'there' "
hi there
So it could work...

Michael Easter said...

@ Adam. Yep, that was a typo: "accepts". The hi/there example works with Groovy 1.1 on my PC. It works with all Groovy version on my Mac.

Danno Ferrin (aka shemnon) said...

It's the space after the semi-colin.

groovy -e " println 'hi'; println 'there' "

Not sure if this is a windows or groovy issue.

Michael Easter said...

@ Danno. Nice! My bet is that it is 'startGroovy.bat' in the bin directory. It has some new stuff starting in 1.5.x