Tuesday, February 9, 2010

Dynamic Typing in Groovy

Groovy like many other features works different from Java when it comes to method binding. Java uses the static binding at compile time to bind the method with the caller based on the parameter types. On the other hand Groovy does method binding at runtime based on the value type of the variable.

Java method binding

public class BindingTest{
public static void main(String[] args){
Object obj1 = 1;
Object obj2 = "hello";

proc(obj1);
proc(obj2);
}

public static void proc(Object obj){
System.out.println("object");
}

public static void proc(String str){
System.out.println("string");
}
}

At execution, the above Java program will print "object" for both the method calls. The reason is Java does "proc()" method binding based on the variable type defined in the call and ignores the actual values.

On the other hand the same Groovy code will print the output based on the variable values at the runtime.

Groovy method binding

def proc(Object obj){
println "object"
}

def proc(String str){
println "string"
}

proc 1
proc "hello"

The above Groovy program will print "object" followed by "string" output upon execution. This capability makes the code clear and concise. Developer can avoid unnecessary type casting in case of method overriding.

One such boilerplate code a Java programmer has to write while overriding the equals() method, which can be avoided with this approach.

// Java way
public boolean equals(Object obj){
if(!(obj instanceof MyType)){
return false;
}

MyType mt = (MyType) obj;
// do equality check
return result;
}

// Groovy way
public boolean equals(MyType mt){
// do equality check;
return result;
}

The Groovy code is quite simple as no type checking or type casting is involved. Besides if the caller will pass any other type of object; the super class version of equals() will be called and as the base equals() checks identity (==, reference equality), it will return false without any additional line of code.

So such small but effective techniques makes Groovy more popular in Java world.

1 comment:

  1. Good binding work in Java programming. I think this is unique and beautiful work done by the blogger on this special topic. I read it completely and recommend it very effective too for others.

    ReplyDelete