Why (at least for me) Groovy sounds like a Java++

I’m a Java guy, and as may sound obsolete to some, but I really like this language. As time goes by, and I start to know better another languages like Groovy or Ruby, I can’t avoid to feel a little envy of those. Java 5 revamped the language, that’s sure, but it still could be a little better.

This is why I really falled in love with Groovy: it really looks like Java, but solved many of it’s boring spots in a really elegant way. So, it’s no surprise that for me Groovy is like a Java++. Here comes a list of the problems solved by Groovy:

Strings

Interpolation:

In Java

int value = 3;
String str = "O valor inteiro vale " + value

In Groovy

int value = 3
String str = "O valor inteiro vale ${value}"

Multiline strings

In Java

String multiline = "This is my string \n" +
"which will have more than one \n" +
"line!"

In Groovy

String multiline = """This is my groovier string with
as many lines I want!
And I don't even need those ugly + operators
anymore!"""

Avoiding a NullPointerException

In Java

Object value = buildObject();
if (value != null) { // bla bla bla }

In Groovy

def value = buildObject()
if (valor) {//bla bla bla}

In Groovy, the truth isn’t always a boolean value. If something is null, so it’s false! Way simpler!

Checking if something is null:
In Java

Object obj = anything();
String str = "The value of this object is  " + obj == null ? "null" : obj.toString(); // Horrible!

In Groovy

Object obj = anything()
String str = "The value will be ${?obj.toString()}" // Clean!

Getters and setters

Let’s face it: it’s really boring to keep writing getters and setters for all our Java Beans, isn’t it? Sure, we have our IDE’s which allow us to do it automatically, but the code in the end is quite ugly don’t you think?

Well, here comes another comparison:

Java

class HotClass {
private int value;
public int getValue() {return this.value;}
public void setValue(int v) {this.value = v;}</em>

<em>private String text;
public String getText() {return this.text;}
public void setText(String v) {this.text = v;}
}

In Groovy…
Groovy

class WayHotterClass {
int value
String text
}

I don’t need to type all those getters and setters. Groovy will generate them for me automatically! Neat, don’t you think?

Optional return

This is a kind of a controversial point, but I really whould like to have something like this in Java. In Groovy, the last command on a code block is interpreted as a return value.

This is a completely personal opinion, but I think it generates a clearer code:

int sum(int a, int b) {
a + b
}

Closures

Closures almost were inserted on Java 7. Well, for a Java developer which never saw them, the big question is: what the hell are those?

Basically closures are another data type which doesn’t store a value, but a set of instructions. This is the most basic description I could find about it. With closures, you can have variables which are in fact executable code, like the following example:

def hotClosure = {
print "\nI'm a closure."
}

And a closure may have parameters too:

def hotClosureWithParameters = {a, b ->
a + b}

And these closures are actually attribures of classes. So you can write something like this:

class Class1 {
def closure = {
"I'm the closure of class 1"
}
}</em>

<em> class Class2 {
def closure = {
"I'm the closure of class 2!"
}
}</em>

<em> Class1 class1 = new Class1()
Class2 class2 = new Class2()
class1.closure = class2.closure // See? I changed the behavior of class1 at runtime!</em>

<em>

Numbers on a numeric way!

When you have to deal with a BigDecimal value in Java is always a pain in the ass. Look at this example:

public BigDecimal delta(BigDecimal a, BigDecimal b, BigDecimal c) {
return b.multiply(b).subtract(new BigDecimal(4).multiply(a).multiply(c));
}

Is it easy to read? How could I do it in Groovy?

public BigDecimal delta(BigDecimal a, BigDecimal b, BigDecimal c) {
(b * b) - (4 * a * c)
}

Wow! Now someone can understand my code!

Dynamic constructors

Let’s suppose that in Java you’ll have a class like this:

class Person {
private String name;
private String address;</em></em>

<em><em> // getters and setters
}

In this class, I’ll have only one constructor, which is the default one. If I want, I can add new ones as I need those, but usually when I try to populate a new instance, I’ll do something like this:

Person person = new Person();
person.setName("Kico");
person.setAddress("Somewhere in Brazil");

How can I do the same thing in Groovy?

Person person = new Person(name:"Kico", address:"Somewhere in Brazil");

<

Way simpler! Three lines of code in a single one! And the best thing here is: I can do exactly the same thing with default Java classes too in Groovy code!

Conclusions

As its shown, these are only a few spots that I really appreciate in Groovy. And what is way cooler is the fact that many of these characteristics were going to be added on Java 7. If they were, it whouldn’t be exaggerated to say that Java whould became Groovy. :)

12 comentários em “Why (at least for me) Groovy sounds like a Java++”

  1. # // Before Java 5
    # String str = “The value is ” + Integer.toString(value);
    # // After Java 5 (way better!)
    # String str = “O valor inteiro vale ” + value

    Both worked before Java 5 — didn’t they? It’s been years ;-)

  2. Rafael Afonso

    There is another way to avoid NullPointerException:

    String str = null
    println str?.size()

  3. As EC member of the JCP, I agree with the positive intentions for Java. I also noticed a POC by Guillaume, one of the Groovy co-founders to integrate it with new Java (JSR) libraries such as JSR-275 (which I also am Spec Lead to) with great delight.
    As well as libraries to extend Grails in ways, Java still doesn’t provide until now like proper Currency handling and conversion…

    Grails and its declared JSR Groovy will however have to follow the same standards every other JSR does. And there it looks not so bright, considering even e EDR has never been proposed sice its “proud instigation” 5 years ago this week ;-)

    Thus currently JSR-241 is inactive. And unless the JCP was to die completely or being replaced by some other form of community, any Groovy or Grails community still has to obey the Java community. Especially if its intention was to bring up something everybody may consider a real “Java 2.0” or “Java++” not just one single vendor or fraction. How that ends Microsoft’s J++ has demonstrated quite clearly I think ;-)

    1. @Werner Keil, Agreed. Actually, I don´t know if it´s a good idea to create a JSR for Groovy.

      I think these languages are great for inspiration, but not to became a standard or something like that. Actually I think that, in this case, as free as it goes, better.

  4. Werner Keil

    @Shantanu I noticed Scala, and it received some hype around it, too lately.
    I cannot say, if this “Yet Another Dynamic Scripting Extension” for Java will be more succesful, than Groovy/Grails, JavaFX or similar approaches? Especially following the Sun takeover by Oracle, some of these may receive either more or less attention.

    At the moment, Scala is still a lot less mature when it comes to real value for Functional or Business/Domain Driven Development. What value does it have, to write a Java project in a slightly different syntax, but be completely missing some of the useful basics, .NET or Delphi (based on Turbo Pascal, Scala’s author worked with the also Swiss founder, Nikolas Wirth earlier ;-) introduced like built-in fast Currency and Money support.

    I am among those, fighting to get this into Java some day, but feel a little dissapointed, all theese DDD Gaga approaches including the examples by its “preachers” like Evans only lead to an ongoing fragmentation of the platform, and no real value for users or developers.

    Grails at least via Plugins has elegantly solved the problem. There Currency support and Converter(!) is offered. If Scala or another approach manages to get there, then I may be tempted to call it Java++, until then it has only Academic value.

  5. Take a look at JSR-310 (new Date & Time API) and also JSR-275 wich aims to solve Units & Measures stuffs in Java. But as far as could see none of them talks about Currency…

  6. Very the good it is with the closure and the Groovie. I like the Groovy because he has the dynamic operationalism and array boundedness inside the thing of itself by the thing in itself which reference him.

Deixe uma resposta

Esse site utiliza o Akismet para reduzir spam. Aprenda como seus dados de comentários são processados.

Rolar para cima