Thursday, February 05, 2009

Getting interested in polyglot programming

From the last few days I have started learning Groovy by listening to the Groovy series podcasts. While listening to the podcast on numbers (attached_code), I couldn't help smiling when I saw this (line 42 in the attached code):


assert 1/2 == 0.5


Yes 1/2 is actually 0.5 in Groovy. Isn't that awesome :-) We all know what we get when we write this code in Java:

System.out.println("1/2 = " + 1/2);

A few other things I found interesting about Groovy numbers are:

def bigDecimalObj = 5.12345
assert bigDecimalObj.class.name == 'java.math.BigDecimal'

Groovy treats all floating point numbers as BigDecimal (there are exceptions, but I will not get into that here). We all know how difficult it is to implement high precision calculations in Java. We cannot use double, because we may lose precision in calculations involving double. The alternative of using BigDecimal results in unreadable code.

However, Groovy can be compiled to bytecode and can coexist with Java. So now we can use the best tool that fits the job. We can continue using Java for most things, but places where we need to do high precision calculations, we can encapsulate that code into Groovy classes.

Slowly but surely I am beginning to see the benefits of polyglot programming.

No comments: