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.
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