Overloading and Smooth Operators
An anonymous reader writes "IBM DeveloperWorks has an interesting article on operator ad hoc polymorphism (operator overloading for the uninitiated). With the increase in Java popularity and their banning of operator overloading (among other things) the author decides to show some of the great benefits that operator overloading can bring, as long as it is served with a 'healthy dose of caution.'"
Sure, there are lots of things you can do with operator overloading, but there are good reasons to avoid them. Ultimately, it comes down to some basic questions:
Will the use of overloading operators...
*) reduce developement time?
*) reduce the number of bugs?
*) improve maintainability?
In most cases, the answer is at best murky. Sure, if you're doing mathematical programming, adding complex numbers, rational numbers (tracking numerators and denominators instead of using floats), or something like that, then it's intiutively a good thing. But in most cases, it's not intuitive. When someone else comes to the project and tries to figure out what's going on, it's like having a bunch of extra macros for them to look up. Function calls make it much more obvious what's going on.
Contrary to the article that states that a++ and ++a can be aliased to one call a.next() this is not how it should be done: ...)
a++ needs to return the value of a BEFORE it is incremented
++a needs to return the value of a AFTER it is incremented
Sorry for the rant, I've just spent too long working with programmers that didn't know the difference
(Not at my current job mind you
Search your logs like the web: splunk!
or
CustomObject1 * (CustomObject2 - CustomObject3 ^ 10)
Operator overloading is too easy to abuse because others won't necessarily understand what a + or - or x, etc. means. I think this post says it all:
//now tell me: //is (to me) much clearer than: // or even than: // or isn't it?
-= cobnet -= wrote:
>
> Now I wonder why Java doesn't allow overriding of operator, because I think
> it makes things a lot easier...
>
> For example... presume you have written a class Point() and that you test
> this class:
> Point p1 = new Point (2,3);
> Point p2 = new Point (46,4);
> Point p3 = new Point (5,8);
> Point p4 = new Point (5,5);
>
> Point p = p1 + p2 + p3 +p4;
>
> Point p = p1.add((p2.add(p3)).add(p4);
>
> Point [] pArray = { p2, p3, p4};
> Point p = p1.add(pArray);
>
It isn't. That seems to be a classic example of abusing operator
overloading. Adding two points together makes absolutely no sense. If
the intent is to create a collection of points, then a Collection should
be used, along with the associated add() methods.
>
> So what made java didn't allow this overriding of operators??
>
A plethora of code similar to your example.
Jim S.
Those who open their minds too far often let their brains fall out.
Hours can be easily wasted if someone redefines something in a way that isn't expected. Especially dinks who make macros so "save time".
----
Go canucks, habs, and sens!
Java Shorthand. -1 TROLOL.
Sure. Because Complex x = (a + b) * c; is so much less readable than Complex x = (a.add(b)).assign(c); .
Java disallowing C++-style constants, operator overloading, templates and everything else useful just adds to the theory that Java is C++ for stupid people.
Used poorly, it results in crap. But does that mean that we should block off entire development tool from programmers?
A properly designed and applied overloaded operator can be a great tool for development.
A poorly designed or inappropriatly applied overloaded operator can create a mess of code and a maintenance nightmare.
Now, replace "overloaded operator" with a blank and fill it in with what ever you like. "data layer", "abstract class", "architexture", etc... But if the powers that be decide that programmers need to be protected from data access, inheritance, and design fundamentals, what the hell are we left with?
-Rick
"Most people in the U.S. wouldn't know they live in a tyrannical state if it walked up and grabbed their junk." - MyFirs
Will the use of overloading operators... *) reduce development time? *) reduce the number of bugs? *) improve maintainability?
If the answer is yes to the above (This is an all or nothing test), then use them, if not don't use them.
There is a good reason that most examples of operator overloading are complex numbers - using overloaded operators for complex numbers reduces development time, reduces the number of bugs, and improves maintainability.
There is a good reason examples of operator overloading never use shapes. While I can design an shape interface where
circle + square
is legal, and gives some useful result. However this will increase development time, increase the number of bugs, and reduce maintainability. Therefore anyone use overloads operators for shape classes is a fool.
Operator overloading is often abused. I rarely find it useful to overload operators, but in those few cases where I overload an operator I make my code better.
The author refers to an older article about Groovy. He does not really say what it is, but it seems to be new scripting language. The Groovy interpreter is a java program. Which means that the JRE is interpreting an interpreter.
:-). I wonder whether it is faster than my first BASIC interpreter on the CPC: about 700 floating point for loops per second, and much more in integer...
I have heard before that performance is no longer relevant, but I have seen few designs that take this opinion so serious
that's why the parent said that for complex numbers, matrices, etc, operator overloading is the right thing to do.
antipaucity
As long as we're limited to few characters that are overloadable, this leads only a short way. What about this: Leave the operators as they are because they are useful (or let people overload them if they don't work as desired) but allow for defining new operators. This is just matter of syntax. You write "x=y+z" instead of "x=add(y,z)". So why not
content >>>> home @ host, *) proto=UDP, *) markas=BULK;
Allow for defining completely arbitrary syntax that way. Sometimes constructs imposed by the language are heavy and uncomfortable. The way around is overloading operators, but if you do, you mostly lose the original, and you have only a few of them. So where are custom operators?
45 5F E1 04 22 CA 29 C4 93 3F 95 05 2B 79 2A B2
Operator overloading is often abused.
That's what I keep hearing, but I've never actually seen anywhere dubious usage of it, such as your "circle + square" example.
Attention zealots and haters: 00100 00100
Which is why I've always called Java "C++ for VB programmers."
Anonymous Cowards suck.
Yeah, that's a lot more readable.
This is precisely why operator overloading is both unneeded and unwelcome. Like an earlier post said, the benefit doesn't even come close to outweighing the price. "<=>" is a perfect, classical example of how programmers get positively drunk with freedom and treat operator overloading like a shiny new toy. Code full of that instead of "compareTo" is an instant eyesore. I'd rather spend my time developing, not deciphering.
The Internet is full. Go away.
*) reduce developement time?
*) reduce the number of bugs?
*) improve maintainability?
In most cases, the answer is at best murky.
Then it follows that avoiding operator overloading is subject to the same test. That's not an argument against operator overloading.
I've seen lots of sucky C++ code, and operator overloading has never been one of the problems -- maybe because sucky C++ code tends to be written by either C or Java programmers ...
I love the smell of hypocrisy in the morning. It smells like... coffee.
Seriously, operator overloading is a powerful technique that, done right, allows you to write clear, expressive, maintainable code. Done wrong it allows you to write foul spaghetti, but any language allows you to write foul spaghetti --- Flon's axiom: There does not now, nor will there ever, exist a programming language in which it is the least bit hard to write bad programs.
Not allowing operator overloading (except when the language authors break their own rules) has no effect other than to reduce the options available to the programmer. It means that while you can't use them in cases where operator overloading is not useful, it also means that you can't use them in cases where operator overloading is useful and would produce better code. It means you can't, for example, create an imaginary number class that works the same way as int or long. This is not the mark of a good, extensible, expressive language.
If your programming language lets you use "+" for more than one numeric type, you use operator overloading. Unless you think adding fp numbers should use a different syntax than adding integers, you're a fan of operator overloading.
An "Ask Slashdot" re the stupidest overloadings we've ever seen might be fun, but discussing whether the functionality is a good idea is absurd. Any discussion should center on when to use it, not whether to use it.
Sheesh, evil *and* a jerk. -- Jade
I cannot see *any* overloading in the examples that make sense. Comparing Lava lamps for size? The ugly shift Sting operator? And what happens if there is a "compareTo()" with an ugly side effect? Will the programmer really check out the implementation of '' like he might have done with the "compareTo()" method?
I hate it when writers are trying to explain something, and then use the most awfull programming constructs to show you how to use the feature. Even if the bad code is unrelated, it still teaches the readers how to do things wrong. In this case, it demonstrates how not to use operator overloading and why it should be avoided. Unfortunately, that was not the writers intention.
For scientific and technical work Fortran has so many other advantages over C/C++ that it is no surprise that it is still in widespread use. The odd thing is that many computer nerds don't know about it.
Operator overloading has been around for a long time. Mathematicians use it all the time. Ever heard of 'matrix multiplication'?
This yields a simple rule of thumb: operator overloading is permissible whenever it is modeled after common mathematical use, so it's ok to use it for matrices, vectors, complex numbers etc. I also grant you string handling (as the Java developers did, too).
In all other cases, it's just stupid, like using '+' to append an event handler to a list of handlers, or '<<' for stream handling, because the semantics are not clear at all.
Are you trolling or do you just like to make sweeping, overgeneralized statements?
8 of 13 people found this answer helpful. Did you?
Security audits (or hell, any type of code audit) becomes a nightmare the more overloading and polymorphism a programmer uses. I HATE having to audit c++ code from even a moderately creative programmer. Honestly, the more of an OO language a programmer uses, the less verifiably secure it will be and it will be trusted less accordingly.
You wish.
It is not a "sweeping, overgeneralized statement" to state how I explain my opinion of Java to people. If you have a different opinion of the language, that's fine. This one is mine. It would be sweeping and/or overgeneralizing if I was stating fact. I was obviously not stating fact, but giving my opinion.
Anonymous Cowards suck.
Since when can't a statement be an opinion? Anyway, what exactly do you mean? It sounds like you're saying that C++ is too difficult for VB programmers, so they use Java. Please correct me if I'm wrong.
8 of 13 people found this answer helpful. Did you?
I don't think its worth explaining or arguing about. It was just a quib. I appologize if it offends you.
Anonymous Cowards suck.
Write the overloading implementation as a series of proofs for interested field so that people can't make shit like << mean anything other than left-shift (multiply by power of two).
For example, to overload "==" make the software implement a routine "comparitor" that returns a structure of public elements that the runtime resolves as comparison itself. To implement String's comparitor, have it return a structure like this: { int; byte[]; }
The result is that the compiler can figure out how to compare that and implement !=, ==, >, >=, <, <= all from one little statement.
To overload arithmatic operations like "+" again, resolve to a graph structure that the compiler can perform sumation on, then a routine that returns that graph structure to the desired (returned) object.
By making overloading this painful, nobody will do it EXCEPT in the one place where it can actually help- things that model numbers. That's because it won't seem like a shiny piece of plastic that programmers can implement in all their classes.
True story:
A CS postgraduate(!) I'm aware of uses C++ like it's going out of style. Every class he implements (which is perfectly documented, I'm sure) overloads every single operator so that they will all have SOME semantic meaning- even if that meaning is to cause the program to die a horrible death.
Unfortunately, the end result is that a language as flexible as C++ produces things like dialects that only those trained in those dialects can work with it. They might be wonderful C++ programmers, but completely incapable of dealing with this code because it's just so different.
String+String is as stupid as FooBazString. It DOES add confusion, and doesn't buy a damn thing. While I am sick of BigNum.add() operations, if that's what is needed to keep these kids from making another pile of shit like C++, then that's what I'll need to use.
That is because you are used to the cout << foo; syntax, so you don't think of it as abuse. Though it can be argued that there is no better way, I don't know if I buy that.
Flamebait, huh? It looks like the Java dweebs have spoken.
Funny, it seems like there are very few actual C++ positions that are not Windoze/MFC positions. So if you want to be a Windoze Weenie, stick with C++/Visual C++ . Sure there's lots of C++ positions around, that don't pay, developing on platforms like KDE and GTK, the the paying positions seem to be few and far between.
Personally I want to get paid to code, and I don't want to code for or on Windoze, so I use Java.
I've also the garbage C++ code produced on the *NX platform. People want to move to Java because it's the only way we can throw out your stuff. If C++ had a working garbage collector, these apps would have deleted themselves a long time ago. C++ Programming Style was written in 1992, C++ Strategies and Tactics was written in 1993, and Effective C++ was written in 1991. You C++ twits have no excuse for putting out the kind of garbage I've seen.
People who complain about Java code being bad have obviously never had to maintain legacy C++ code.
If someone is passing you on the right, you are an asshole for driving in the wrong lane.
What hell are you talking about. I've been programming in C++ for years, very little of which was for Windows. Maybe you should expand your horizons. There is a whole world beyond hosted systems.