With the rise of languages that support operator overloading like Ruby, Groovy, Scala and C# one is justified to wonder if libraries will become loaded with unreadable APL like
code.
I have already seen signs of the potential chaos that could come from the abuse of operator overloading. In the Scala actor library tutorial for example I have seen the following:
producer ! Next
I am totally unable to guess the meaning of this.
This example is from a Ruby library:
(aobject / 'a string')
In this case because I watched the full presentation I know that the slash is actually an alias for a search method.
The speaker in the presentation was calling this cool. I call it stupid. It is the archetypal example of a bad use of operator overloading. The presenter himself said he was puzzled and could not understand what the code was doing at first. Definitely not cool.
Since I’m looking at switching to Scala as a main language I thought I needed to think about what kind of rule I would put into our code convention document under the section
Operator Overloading
. I thought I would share this with others to get inputs and hopefully constructive comments.
For me, the best applications of operator overloading makes the code easier to understand.
Here are some example of this:
myWeight > aWeight
Beware of things like:
myDog > otherDog
where we don’t exactly know how things are being compared.
All other uses of operator overloading is suspicious. The worst offenders of course are operators used as meaningless abbreviations for method names.
In some cases you will have to watch for compiler quirks and language peculiarities. WIth C# for example when you define the ++ operator on a class it has the same semantic when used as a prefix (pre increment) or
suffix (post increment). In both cases this works like a pre increment operation. This is a bug factory.
In this case I think the compiler should give an error when ++ is used as a post increment operation because it will not have the expected result. You get the same thing with the — operator.
How would you modify this and what would you add to it ?
JS