From Java to Groovy in a few easy steps

From Java to Groovy in a few easy steps

 

Groovy and Java are really close cousins, and their syntaxes are very similar, hence why Groovy is so easy to learn for Java developers. The similarities are such that most of your Java programs are even valid Groovy programs! However, as you learn Groovy, you'll get used to its neat shortcut notations, its sensible defaults, its GStrings, and more.

In this first article, we are going to take a Java program and turn it into a Groovy program. We'll start with a dumb but convoluted Hello World program, and in later articles, we may see some more advanced examples. For this one, I've taken my inspiration from some slides that are presented at conferences to show how Groovy and Java syntaxes are close -- thanks to Andres and Paul for this idea.

So what does our initial Java program looks like?

  1. public class HelloWorld {  
  2.     private String name;  
  3.   
  4.     public void setName(String name) {  
  5.         this.name = name;  
  6.     }  
  7.   
  8.     public String getName() {  
  9.         return name;  
  10.     }  
  11.   
  12.     public String greet() {  
  13.         return "Hello " + name;  
  14.     }  
  15.       
  16.     public static void main(String[] args) {  
  17.         HelloWorld helloWorld = new HelloWorld();  
  18.         helloWorld.setName("Groovy");  
  19.         System.out.println( helloWorld.greet() );  
  20.     }  
  21. }  

Well, this HelloWorld class has got a private field representing a name with its associated getter and setter. There's also a greet() method which will return the infamous Hello World string we've all come to love and hate at the same time. Then there's a main() method that will instantiate our class, set the name, and print the greeting message on the output.

What will the Groovy program look like?

 

  1. public class HelloWorld {  
  2.     private String name;  
  3.   
  4.     public void setName(String name) {  
  5.         this.name = name;  
  6.     }  
  7.   
  8.     public String getName() {  
  9.         return name;  
  10.     }  
  11.   
  12.     public String greet() {  
  13.         return "Hello " + name;  
  14.     }  
  15.       
  16.     public static void main(String[] args) {  
  17.         HelloWorld helloWorld = new HelloWorld();  
  18.         helloWorld.setName("Groovy");  
  19.         System.out.println( helloWorld.greet() );  
  20.     }  
  21. }  

Yes, that's exactly the same program! No, I'm not kidding, that's really the same program in Java and in Groovy! I wouldn't really call it a Groovy program though, as we can definitely improve it to make it more concise and readable. We'll do so by following some simple steps to "groovyfy" the program. The first step will be to remove the semi-colons:and at the same time, I will also remove the public keyword as by default classes and methods are public in Groovy, unless stated otherwise explicitely. Our Groovy program now becomes:

  1. class HelloWorld {  
  2.     private String name  
  3.   
  4.     void setName(String name) {  
  5.         this.name = name  
  6.     }  
  7.   
  8.     String getName() {  
  9.         return name  
  10.     }  
  11.   
  12.     String greet() {  
  13.         return "Hello " + name  
  14.     }  
  15.       
  16.     static void main(String[] args) {  
  17.         HelloWorld helloWorld = new HelloWorld()  
  18.         helloWorld.setName("Groovy")  
  19.         System.out.println( helloWorld.greet() )  
  20.     }  
  21. }  

What else can we do? We can use Groovy's special strings: the GString. Isn't that a sexy feature? But what is a GString? In some other languages, it is also called an "interpolated string". Inside a normal string delimited by double quotes, you can put some place holders, delimited with ${someVariable}, that will be replaced by the value of the variable or expression when the string will be printed. So you don't need to bother about manually concatenating strings. So what will our greet() method look like?

  1. String greet() {  
  2.     return "Hello ${name}"  
  3. }  

One more baby-step further: you can omit the return keyword and the last evaluated expression of your method will be the return value. So greet() is now even slighlty shorter. Let's recap to see the current state of our program:

  1. class HelloWorld {  
  2.     private String name  
  3.   
  4.     void setName(String name) {  
  5.         this.name = name  
  6.     }  
  7.   
  8.     String getName() { name }  
  9.   
  10.     String greet() { "Hello ${name}" }  
  11.       
  12.     static void main(String[] args) {  
  13.         HelloWorld helloWorld = new HelloWorld()  
  14.         helloWorld.setName("Groovy")  
  15.         System.out.println( helloWorld.greet() )  
  16.     }  
  17. }  

I've even taken the liberty to turn the getName() and greet() methods into one-liners. But then, what's next? Groovy supports properties -- a future version of Java may also support them. So, instead of creating a private field and writing a getter and setter, you can simply declare a property. In Groovy, properties are very simple since they are just mere field declaration without any particular visibility. Our name property will be just String name, nothing more. A private field and associated getter and setter will be provided for free by Groovy. For calling setName(), you'll be able to write helloWorld.name = "Groovy", and for getName(), simply helloWorld.name. This also means that you will also be able to call getName() and setName() from a Java program invoking our Groovy class. Let's see our new iteration:

  1. class HelloWorld {  
  2.     String name  
  3.   
  4.     String greet() { "Hello ${name}" }  
  5.       
  6.     static void main(String[] args) {  
  7.         HelloWorld helloWorld = new HelloWorld()  
  8.         helloWorld.name = "Groovy"  
  9.         System.out.println( helloWorld.greet() )  
  10.     }  
  11. }  

Groovy gives you some handy methods and shortcuts for some mundane tasks such as printing. You can replace System.out.println() with println(). Groovy even decorates the JDK classes by providing additional utility methods. And for top-level statements (a statement which is just a method call with some parameters), you can omit parentheses.

  1. class HelloWorld {  
  2.     String name  
  3.   
  4.     String greet() { "Hello ${name}" }  
  5.       
  6.     static void main(String[] args) {  
  7.         HelloWorld helloWorld = new HelloWorld()  
  8.         helloWorld.name = "Groovy"  
  9.         println helloWorld.greet()  
  10.     }  
  11. }  

So far, you've certainly noticed that we used strong typing all over the place by defining the type of every method, variable or field. By Groovy also supports dynamic typing. Thus we can get rid of all the types if we wish so:

  1. class HelloWorld {  
  2.     def name  
  3.   
  4.     def greet() { "Hello ${name}" }  
  5.       
  6.     static main(args) {  
  7.         def helloWorld = new HelloWorld()  
  8.         helloWorld.name = "Groovy"  
  9.         println helloWorld.greet()  
  10.     }  
  11. }  

We transformed the strings into the def keyword, we were able to remove the void return type of the main method, as well as the array of string type of its parameter.

Groovy is an Object-Oriented language (a real one where numbers are also objects), and it supports the same programming model as Java. However, it's also a scripting language as it allows you to write some free form programs that don't require you to define a class structure. So in the last step of this tutorial, we're going to get rid of the main method altogether:

  1. class HelloWorld {  
  2.     def name  
  3.     def greet() { "Hello ${name}" }  
  4. }      
  5.   
  6. def helloWorld = new HelloWorld()  
  7. helloWorld.name = "Groovy"  
  8. println helloWorld.greet()  

A script is really just a bunch of statements thrown freely into your program. You can even define several classes inside a script if you will, just like our HelloWorld class.

Voila! Our boring Java program became much more Groovy, by following some simple baby-steps as we learned how to leverage some of the numerous handy features that the Groovy language provides. The program became much more concise, and at the same time more readable than its Java counterpart. Readability is so important when you have to maintain code, especially if it's not yours, as we usually spend much more time reading and understanding code than actually writing it.

In forthcoming installments, we will learn more about the language, its syntax and its APIs which simplify the life of the Java developer. We will learn about its native syntax for lists, maps, ranges and regular expressions, and much more. Stay tuned!

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值