Wednesday, September 19, 2012

Groovy Day 3 : operators overloading

Back in 2009, when I learned C# for a Microsoft Contest (Imagine Cup) I was wondering why Java has no operator overload mechanisms. After discussion and thinking, the problems are the readability and possible deratives. Firstly the readability because it could disturb the newbies when they see a code where an element is added to a list using a +=. It is not always clear, depending on the language, which method is called internally. The second problem comes from the first one in some sense. You could imagine a new way of code obscuration when you implement the addition with a minus symbol or the append on String with a division symbol. Just imagine the chaos that could appear.
Groovy resolves the first problem by giving a limited set of symbol that can be overload. For example, the constructor operator cannot be overloaded. This limited choice reduces the potential mistakes. Then Groovy provides by its JDK (Java development kit) some common operators that follow standards. Additionally  the operators are linked to named methods, this provide a certain security for the new developers. They could easily use the normal methods to do their stuff.
Stop the theory, let's show some examples !
// initialization of a list using Groovy facilities
List list = []
// append 'hello' to the list
list.add('hello')
// without parenthesis this time
list.add 'world'
// using leftShift method
list.leftShift('too')
// using the symbol leftShift
list << 'other'

assert list == ['hello', 'world', 'too', 'other']

You can see in the previous example the use of assert at the end. In Groovy world, the assert is used to show the user expected results. One problem, the assert are not removed like in Java for the production code, so keep them for Unit Testing or demonstration like this one. To come back to the example, the leftShift method is implemented like this in the JDK :
public <T> Collection<T> leftShift(T value) {
   this.add(value);
   return this;
}
Actually it's not directly implemented like this, but the result is the same, we will come back to how Groovy adds methods to the existing class in an advance tutorial. If you are curious and impatient, just search for Metaprogamming on your favorite search engine.
So you can see that Groovy implements the different operator overloading like simple method that take advantage of existing code. This has the advantage to keep the compatibility with old code that use method calls.
To have more information on the subject and find a mapping table between operator and method names, please follow this link : Operator Overloading

No comments:

Post a Comment