Thursday, November 18, 2004

Java and operator overloading

A consistent form of amusement since the beginning of Java is how the designers bashed operator overloading in C++, without really examining the problem, which is basically that operator overloading in C++ is complex and hard for the programmer to get right.

However, with a garbage collector and other improvements afforded by Java and C#, operator overloading becomes fairly straightforward, as the Java designers would have noticed had they looked at Python, a language which predates Java and which supports operator overloading without any fuss. C# has since demonstrated that operator overloading could have been added to Java without making it painful (at this point in Java's lifetime, however, there are probably more important problems to be solved).

In the meantime, Java's String class with its + and += shows how difficult it was for the Java designers to excluded operator overloading from the language. Sometimes operators are helpful. Or, put another way, the thing about syntactic sugar is that it's sweet.

I thought of all this when I came across the following in the Javadocs for BigDecimal:

For the sake of brevity and clarity, pseudo-code is used throughout the descriptions of BigDecimal methods. The pseudo-code expression (i + j) is shorthand for "a BigDecimal whose value is that of the BigDecimal i added to that of the BigDecimal j."

Whoever wrote this class was clearly missing operator overloading.