Operator Overloading: Trickier Than it Looks

Monday, October 8th, 2007

In this illuminating post Stephen Colebourne demonstrates exactly why operator overloading is a bad idea. Now mind, you, he doesn’t think that’s what he’s doing. He actually believes he’s making the case for operator overloading. However the mistakes he makes are exactly the sort of mistakes likely to be made by almost anyone without at least an undergraduate degree in mathematics who tries to overload +, -, *, and especially /. If you don’t know the difference between a group, a ring, and a field, you have no business overloading operators.

Now I’m not saying that one has to take a course in abstract algebra before you can be a competent programmer. You don’t as long as the language you program in doesn’t support operator overloading (or as long as you’re wise enough not to use it if it does). However since most programmers are didn’t get beyond ODEs in college (if indeed they got that far–some of my comp sci friends struggled mightily with calculus and had to retake it repeatedly), one can’t responsibly design a language that requires mathematical sophistication in the 99th percentile for proper use. Probably one should stop with high school algebra.

Features that are guaranteed to be misused should be eliminated. In the specific case of operator overloading, I daresay, the feature will be misused far more often than it will be used properly. There are only about a dozen or so cases where operator overloading is called for, and only one is even remotely common. That one is complex arithmetic, and this single use case could be better handled by adding a complex type to the language. Arguably BigDecimal and BigInteger are a second and a third. The remaining cases are so incredibly esoteric that only a mathematician or an occasional physicist could possibly be interested in them. Can anyone name even one?