Beta

×

Welcome to the Slashdot Beta site -- learn more here. Use the link in the footer or click here to return to the Classic version of Slashdot.

Thank you!

Before you choose to head back to the Classic look of the site, we'd appreciate it if you share your thoughts on the Beta; your feedback is what drives our ongoing development.

Beta is different and we value you taking the time to try it out. Please take a look at the changes we've made in Beta and  learn more about it. Thanks for reading, and for making the site better!

Overloading and Smooth Operators

ScuttleMonkey posted more than 8 years ago | from the i-left-caution-in-my-other-pants dept.

Java 75

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.'"

cancel ×

75 comments

Sorry! There are no comments related to the filter you selected.

Useful? Doubtful. (4, Insightful)

crow (16139) | more than 8 years ago | (#13883168)

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.

Re:Useful? Doubtful. (1, Flamebait)

keesh (202812) | more than 8 years ago | (#13883243)

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.

Re:Useful? Doubtful. (1)

VolciMaster (821873) | more than 8 years ago | (#13883793)

that's why the parent said that for complex numbers, matrices, etc, operator overloading is the right thing to do.

Re:Useful? Doubtful. (0, Flamebait)

drxenos (573895) | more than 8 years ago | (#13884237)

Which is why I've always called Java "C++ for VB programmers."

Re:Useful? Doubtful. (1)

cerberusss (660701) | more than 8 years ago | (#13887990)

Are you trolling or do you just like to make sweeping, overgeneralized statements?

Re:Useful? Doubtful. (1)

drxenos (573895) | more than 8 years ago | (#13888469)

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.

Re:Useful? Doubtful. (1)

cerberusss (660701) | more than 8 years ago | (#13888771)

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.

Re:Useful? Doubtful. (1)

drxenos (573895) | more than 8 years ago | (#13889025)

I don't think its worth explaining or arguing about. It was just a quib. I appologize if it offends you.

Re:Useful? Doubtful. (0)

Anonymous Coward | more than 8 years ago | (#13888446)

Anonymous Cowards suck.

You wish.

Re:Useful? Doubtful. (0)

Anonymous Coward | more than 8 years ago | (#13895559)

Flamebait, huh? It looks like the Java dweebs have spoken.

Re:Useful? Doubtful. (1)

Fujisawa Sensei (207127) | more than 7 years ago | (#13916073)

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.

Re:Useful? Doubtful. (0)

Anonymous Coward | more than 8 years ago | (#13940413)

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.

Re:Useful? Doubtful. (2, Interesting)

bluGill (862) | more than 8 years ago | (#13883547)

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.

Re:Useful? Doubtful. (1)

Bill Dog (726542) | more than 8 years ago | (#13884024)

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.

Re:Useful? Doubtful. (1)

bluGill (862) | more than 8 years ago | (#13889559)

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.

Re:Useful? Doubtful. (1)

jgrahn (181062) | more than 8 years ago | (#13884464)

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.

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 ...

Re:Useful? Doubtful. (1)

clive_p (547409) | more than 8 years ago | (#13887610)

I think the problem with overloading in languages like C++ and Groovy is that they only allow you to overload existing operators. If you use a more advanced language like Fortran (in any recent standard such as F90/F95/F2003) you find that you can invent your own operators. If, for example, you want a fuzzy matching operator (similar to LIKE in SQL for example) then you can call it .like. - no need to overload == or something that has not quite the right name. If you want set operators no need to overload + and * since their meaning may no tbe quite obvious: just invent .union. .intersection. and so on. And of course you can overload these for as many data types as you want.

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.

A++ and ++A are NOT the same (4, Insightful)

GaelTadh (916987) | more than 8 years ago | (#13883188)

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 ...)

Re:A++ and ++A are NOT the same (1)

MindStalker (22827) | more than 8 years ago | (#13883457)

I'm not sure exactly what he is saying. I think he is saying that with groovy you HAVE to use a.next().. Which is stupid.

Re:A++ and ++A are NOT the same (1)

fforw (116415) | more than 8 years ago | (#13884233)

my first thought was "Hey there's a difference!", too.. until I realized that the call to a.next() is equivalent to the ++ part:

++a : call a.next() and evaluate a

a++ : evaluate a and call a.next() then.

and I think we can agree that sane programs should use the same operator overloading for ++ in both cases.

Re:A++ and ++A are NOT the same (1)

GaelTadh (916987) | more than 8 years ago | (#13885991)

Sure but the call for a++ should be { b = a; //Creates a copy ! a.next(); return b; } and ++a { a.next(); return a; } //No copy created

Re:A++ and ++A are NOT the same (0)

Anonymous Coward | more than 8 years ago | (#13895480)


  my first thought was "Hey there's a difference!", too.. until I realized that the call to a.next() is equivalent to the ++ part:

++a : call a.next() and evaluate a

a++ : evaluate a and call a.next() then.
and I think we can agree that sane programs should use the same operator overloading for ++ in both cases.

No it's not. You, and most of the people in this thread, have forgotton that a++ must return a COPY of a (before calling a.next()), wheras ++a returns the object itself. It's why people these days tell you to use ++a in those for loops instead of the usual a++.

As for operator overloading in general, it's useful when the underlying concept makes sense. Numerical libraries are the canonical example, but there are many places where overloading equality, less-than, and greater-than makes sense. Basically, if you can tell what the operator should do just by reading an example of it's usage, then overloading that operator makes sense.

Re:A++ and ++A are NOT the same (1)

Intron (870560) | more than 8 years ago | (#13896115)

"Basically, if you can tell what the operator should do just by reading an example of it's usage, then overloading that operator makes sense."

Its a reasonable argument. The problem is the variable "you". As an example, what seems obvious to programmer A might not make sense to programmer 2.
 

Custom object (1)

phoenix.bam! (642635) | more than 8 years ago | (#13883211)

CustomObject1.multiplyBy(CustomObject2.subtract(Cu stomObject3.raisedTo(10)))

or

CustomObject1 * (CustomObject2 - CustomObject3 ^ 10)

Re:Custom object (1)

user317 (656027) | more than 8 years ago | (#13885235)

This is a really bad example. I hope are using CustomObject as a numerical value, then you can just inherit from your favorite numerical type. Its when you are not using custom object as a numerical value then you get into trouble. is customobject1*customobject2 the same thing as sum(customobjects1) custtomobject2 times? can i integrate over customobjects? whats the square root of customobject1? wtf does it mean to multipy two objects which have no numerical value. unless you are writing a phd in abstract algebra you really dont need this.

Re:Custom object (1)

Haeleth (414428) | more than 8 years ago | (#13890289)

You are making the false assumption that languages either support operator overloading, or restrict operators to the predefined basic set. This is simply not true.

Languages of the ML family, for example, permit the definition of arbitrary new operators, they just don't permit you to overload existing operators. This means that when you see +, you know it will be adding two numbers, not concatenating two collections or whatever. But if you want an operator to concatenate your collections, you can define one.

Your silly example in OCaml would normally become
CustomObject.mul obj1 (CustomObject.sub obj2 (CustomObject.power obj3 10))
Which is, indeed, rather verbose and hard to read. But defining new operators is trivial:
let ( *& ) = CustomObject.mul
and ( -& ) = CustomObject.sub
and ( ^& ) = CustomObject.power;;
 
obj1 *& (obj2 -& (obj3 ^& 10))
Still somewhat ugly, but practically as readable as your "good" example, and it has the advantage that this way you can still get fast static typechecking without needing to verbosely declare types like in C++ or Java (I'll take the stuff above any day over writing thirty lines of CustomObject myCustomObject = new CustomObject();. (Besides, the amount of programming I've done where I've had objects similar enough to numbers for me to want to use operators on them is minimal. Overloading is very nice for scientific computation, but most programmers don't actually do scientific computation)).

In Haskell, meanwhile, while operator overloading is available, you can also use any binary function infix: your silly example would quite naturally become
object1 `multiplyBy` (object2 `subtract` (object3 `raisedTo` 10))
I would contend that that is every bit as readable as the version with operators... and it has the clear advantage that by using words rather than symbols, you can have nice pretty infix forms that actually say what they do, instead of using and stream IO.

Really, it's a case of picking the disadvantage you hate least: slow code, verbose type declarations, dynamic typechecking, or no overloading. C++ picks the verbosity; Haskell the slowness; ML the lack of overloading. Languages like Ruby pick slow code and dynamic typechecking, which is strange, but some people seem to like it.

comp.java.lang.programmer 2001 (2, Insightful)

Mr. Competence (18431) | more than 8 years ago | (#13883235)

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:

-= 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);
> //now tell me:
> Point p = p1 + p2 + p3 +p4;
> //is (to me) much clearer than:
> Point p = p1.add((p2.add(p3)).add(p4);
> // or even than:
> Point [] pArray = { p2, p3, p4};
> Point p = p1.add(pArray);
> // or isn't it?

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.

Re:comp.java.lang.programmer 2001 (3, Insightful)

Short Circuit (52384) | more than 8 years ago | (#13883362)

When did you last take a Physics class? Adding points (or non-C++ vectors) is a very, very common thing.

It's extremely useful for solving, i.e. the following two problems.

  • You have four masses of 1 kg each, at (0,3), (2,-1), (4,0) and (2,7). Where is your center of mass?
  • John, Jude and July are walking home from work. John lives one block north of his workplace. Jude lives two blocks north and one block east of John. July lives four blocks west of Jude. How many blocks east, and how many blocks north, does July live from work?


...And those are pretty mundane examples. There're more.

Re:comp.java.lang.programmer 2001 (1)

heinousjay (683506) | more than 8 years ago | (#13883818)

Adding points (or non-C++ vectors) is a very, very common thing.

I'm not disagreeing with you, per se, but this is true only for vanishingly small values of common.

Re:comp.java.lang.programmer 2001 (1)

Short Circuit (52384) | more than 8 years ago | (#13883892)

It's common for physics programming. And some of the largest computing projects in the world are all about physics.

That's one of the main reasons why huge clusters get built...to perform simulations and process physics data.

Re:comp.java.lang.programmer 2001 (1)

heinousjay (683506) | more than 8 years ago | (#13883976)

Yeah, I understood that part, and I don't disagree that it's common within certain fields - just that the entire field is esoteric when you consider the programming community at large. You said "very, very common" initially, which I'd personally reserve as a description for something like, say, concatenating strings.

To make a car analogy (why the hell not... it seems like a good one) it's kind of like saying bumping another car is a common technique (the word 'technique' is important to my meaning). From the perspective of a race car driver, it sure is, but most drivers don't engage in it during their commute.

Re:comp.java.lang.programmer 2001 (1)

Short Circuit (52384) | more than 8 years ago | (#13884086)

Point taken, chewed and swallowed.

I still think it's useful, though I can't come up with any examples not solvable by other methods. But the nice thing about C++ is, like Perl, There's More Than One Way To Do It.

Also, I don't think a language should be designed around keeping a stupid programmer or project team from shooting themselves in the foot.

Re:comp.java.lang.programmer 2001 (1)

heinousjay (683506) | more than 8 years ago | (#13884214)

Also, I don't think a language should be designed around keeping a stupid programmer or project team from shooting themselves in the foot.

I definitely agree with you there. It's not like the 'eye on safety' in Java has prevented people from writing some of the ugliest code on earth.

Re:comp.java.lang.programmer 2001 (1)

Bill Dog (726542) | more than 8 years ago | (#13884281)

Also, I don't think a language should be designed around keeping a stupid programmer or project team from shooting themselves in the foot.

Well, all languages are designed with some safety features, like type checking. There really isn't anything wrong with different languages designed for not only different problems, but different skill levels. When Java was introduced it was touted as the language "for the rest of us". That's fine, not everyone has a CS degree and wants to get down to the C or C++ level. During the dot-com heyday I did a short stint at a VB shop. No one there was CS degreed, they were all IS majors, and some of them once commented they have no interest in dicking with pointers etc., they're only interested in solving business problems. That's fine. For me, I like to get a little geekier, and have more control/flexibility. I like using abstractions in C++ like operator overloading to shield me from lower-level details when I'm not interested at the moment, but giving me the ability to look deeper when/if I need to.

Re:comp.java.lang.programmer 2001 (1)

jericho4.0 (565125) | more than 8 years ago | (#13886865)

"vanishingly small values of common"? Just because it's not in 'Learn Java in 21 Days" doesn't make it exotic. Every game, graphics routine, audio/video codec, and more touch on vectors.

Re:comp.java.lang.programmer 2001 (1, Insightful)

Anonymous Coward | more than 8 years ago | (#13883474)

Adding two points together makes absolutely no sense.

No, it doesn't. And you'll note that this has nothing to do with operator overloading. Without it, he's still doing p2.add(p3), which is equally meaningless but more verbose.

OTOH, if you have to do, say, fixed point math in J2ME, you end up with code that looks like the bastard child of Lisp and Perl.

There are many wrong places for operator overloading, but it's indispensible for the right places.

Re:comp.java.lang.programmer 2001 (1)

kimhanse (60133) | more than 8 years ago | (#13884641)

Adding "points" in 2d is the same as adding compex numbers. The only problem with his example was that he didn't call his "points" vectors.

Re:comp.java.lang.programmer 2001 (1)

TomorrowPlusX (571956) | more than 8 years ago | (#13891342)

I suppose you've never done any sort of complicated 3d or other sorts of geometry programming?

Frankly, having point/matrix/quaternion/plane/etc classes with reasonably chosen operator overloading allows me to condense a LOT of code into quite little, with as far as I can tell a general *increase* in legibility.

When I started doing 3d programming, for robotics simulation, I used a typedef'd float[4] for vertices, and float[16] for matrices. I had C functions for adding, dot products, cross products, matrix multiplication, etc. It worked. But the code was LONG and verbose. Temporaries were scattered all over the place, and in general, the code wasn't self documenting, so I had to not just explain the algorithm, but why the code I wrote performed said algorithm.

Eventually I decided to rewrite all my core maths as proper C++ classes with reasonably chosen operator overloads. On average, heavy code that did a lot of geometric math was reduced in line-count by 50 to 75%. Plus, the code actually read like the human-readable algorithmic description. Best of all, since the code became easier to read, I caught a few minor bugs.

Sure, I'm not saying operator overloading is right when you'r talking about, say, adding a button to a window. But it has its uses. Consider, the whole world is not necessarily just writing database apps. There's a lot of different stuff out there, and limiting programmer's choices is erring on the side of caution a little too far.

P.S. In your quoted code sample, you *clearly* don't understand what the original author was trying to perform.

Use it wisely or not at all. (1)

Goalie_Ca (584234) | more than 8 years ago | (#13883238)

Hours can be easily wasted if someone redefines something in a way that isn't expected. Especially dinks who make macros so "save time".

Re:Use it wisely or not at all. (0)

Anonymous Coward | more than 8 years ago | (#13886288)

Or functions! I hate it when they redefine those. Dorks. What are they thinking? Creating abstractions is completely unprofessional.

That's why I write all my code in raw machine language. If I ever get this program finished, it's going to be completely bug-free, because there are no pesky macros, functions, or other abstractions for bugs to hide behind!

LOL "loss of a valuable shorthand" (1)

Anonymous Crowhead (577505) | more than 8 years ago | (#13883239)

Java Shorthand. -1 TROLOL.

Like any tool (3, Insightful)

RingDev (879105) | more than 8 years ago | (#13883476)

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

Re:Like any tool (2, Insightful)

AuMatar (183847) | more than 8 years ago | (#13884453)

But thats the design theory of Java. I'm not saying I agree with it, but there it is. For example- why no pointers in Java? THey're useful in many situations, and by a competent user they are no more bug prone than any other method. But Java disallows them to protect you from the idiot programmer.

If you want an OO language that doesn't try to hedge the coder in with rules for his own good, you aren't programming in Java. You're using C++. If you don't care for inheretance and templates, you may even go staight C. Other than that, most languages these days place safety nets everywhere to annoy you.

Re:Like any tool (2, Insightful)

RingDev (879105) | more than 8 years ago | (#13884896)

True, but a poorly designed overloaded operator can result in confusing/buggy code. A poorly designed pointer math function can result in overwriting memory that belongs to some other process.

Its one thing to protect an environment from a stupid coder. Its another to protect a stupid coder from themselves.

-Rick

Re:Like any tool (0)

Anonymous Coward | more than 8 years ago | (#13886059)

A poorly designed pointer math function can result in overwriting memory that belongs to some other process.
Just not true, at least in the context of any even close-to-modern operating system.

Re:Like any tool (1)

RingDev (879105) | more than 8 years ago | (#13888530)

Some OSs will attempt to protect one application from another, but usually at the cost of one or both of the applications. And that will not protect you from multiple processes inside one application, or multiple variables in one process. Also, there are still a lot of people still running Windows '98 out there. Is it close-to-modern? Maybe not, but it is common.

-Rick

What is this Groovy? (1)

thsths (31372) | more than 8 years ago | (#13883678)

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 have heard before that performance is no longer relevant, but I have seen few designs that take this opinion so serious :-). 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...

Re:What is this Groovy? (4, Informative)

Shelrem (34273) | more than 8 years ago | (#13883751)

You're entirely wrong. Groovy is another language that targets the JVM. Groovy is either compiled to Java bytecode (and from there, JIT compiled to machine code by the JVM), or it's compiled at runtime in a JIT fashion. There is no interpreter written in Java that runs Groovy code. Groovy is just another language that targets the JVM.

The benefit from all this is that in Groovy, you can interface to Java classes with literally no overhead. It's a brilliant idea for a new language because all the libraries are already there! This skips past one of the biggest stumbling blocks for new lanaguages.

All in all, Groovy's a pretty interesting language that's worth looking into, but apparently you can't be bothered to do a Google search.

Re:What is this Groovy? (1)

pthisis (27352) | more than 8 years ago | (#13891658)

You're entirely wrong. Groovy is another language that targets the JVM. Groovy is either compiled to Java bytecode (and from there, JIT compiled to machine code by the JVM), or it's compiled at runtime in a JIT fashion. There is no interpreter written in Java that runs Groovy code. Groovy is just another language that targets the JVM.

This is indeed a good way to integrate seamlessly with Java.

Jython takes the same approach with Python (Python source is compiled to Java bytecodes) to allow tight Java integration. It has a nice intereactive shell (dynamically compiles to Java bytecodes) so you can do dynamic experimentation/debugging of large Java programs. Pretty cool.
http://www.jython.org/ [jython.org]

Re:What is this Groovy? (1)

Fujisawa Sensei (207127) | more than 7 years ago | (#13916182)

Have looked at Groovy. Its been around for years, and still hasn't delivered on what's promised. Its all hype, and pretty useless for anyting non-trivial.

Check JRuby [sourceforge.net] for the 90% solution.

As long as we're limited to few characters... (1)

SharpFang (651121) | more than 8 years ago | (#13883797)

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?

Re:As long as we're limited to few characters... (1)

fishybell (516991) | more than 8 years ago | (#13884272)

That's exactly what I was thinking.

Unfortunately I know that there exists no language (it might be possible in some scripting languages) that has such a feature. Perhaps when I get around to finishing MODL2 (my own damn language, the second) I'll add in not just operator overloading, but operation definition.

Example custom operators that would be useful:

  • Scope resolution ( :: ) for runtime polymorphism
  • Member of ( . and -> ) for runtime polymorphism
  • Function ( () ) for arbitrary argument order and named arguments
  • Comma ( , ) for tuples
  • Test ( ? : ) for whole object testing

All of these things can either be built into the language, or just worked around (since I have no idea why anyone would actually want to throw formal syntax to the wind), but as an academic exercise, these could be rather useful things to have in a compiled language.

Another, rather odd, and probably too hard to define, idea would be overloading the return value. It would require strict casting, but would mean that you could use a simple if statement to determine if an object (eg. if(mConnection) ) was valid instead of using a method (eg. if(mConnection.isConnected()). You could also create a garbage collector that would get around the accidental copying of pointers by completely preventing it (eg. someFunc(garbageCollectedObjectPointer) would work the same as someFunc(*garbageCollectedObjectPointer)).

Alright, I should stop dreaming and get back to coding.

Re:As long as we're limited to few characters... (1)

pthisis (27352) | more than 8 years ago | (#13889425)

Unfortunately I know that there exists no language (it might be possible in some scripting languages) that has such a feature. Perhaps when I get around to finishing MODL2 (my own damn language, the second) I'll add in not just operator overloading, but operation definition

Most languages with real (not preprocessor) macro support (notably LISP, Scheme, Dylan) support this.

Re:As long as we're limited to few characters... (1)

feijai (898706) | more than 8 years ago | (#13899741)

Since neither Lisp, Scheme, nor Dylan (in its Lisp form anyway) support operators at all your statement is curious. By which I mean, untrue. Now it's true that Common Lisp supports read-macro characters. But AFAIK it does _not_ support read-macro characters which extend the parser in a non-LL fashion so as to provide inline operators. That is, you can't make a read-macro called + which can be called like this: a + b. Because 'a' has already been parsed, evaluated, and completed. Oh, sure you can hack up some ugliness like +(a b), but that's basically a function now, isn't it.

Re:As long as we're limited to few characters... (1)

pthisis (27352) | more than 7 years ago | (#13917900)

Yes, you're right. Please disregard my parent post.

Re:As long as we're limited to few characters... (2, Insightful)

Anonymous Coward | more than 8 years ago | (#13886201)

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. [...] Allow for defining completely arbitrary syntax that way.

As usual, there already is a language that allows this, and (as usual) it's called Lisp. :-)

First, in Lisp, + is not a special case in the syntax: it's the name of a function, like anything else. If you want to define a function called *#@!*, there's nothing stopping you. (You can name them pretty much anything, IIRC, but if it has something crazy like whitespace in the function name, you'd obviously have to escape/quote it.)

A lot of people don't like writing some things in prefix notation, so: Second, Lisp (at least Common Lisp) has "reader macros", which let you define your own syntax for the reader. This is possible due to a few (related) reasons: Lisp doesn't really have a syntax -- you're basically writing the ASTs directly -- and all the language is available all the time -- so you can write code to write code at read-time. You can write a reader macro to parse arithmetic in infix notation (like C), for example, and then embed that in your Lisp program.

If you're doing a lot of network transfers and think a special syntax for that would be handy, you can write a function to rewrite your own syntax into Lisp (at read-time, before it gets to the compiler, so it's still compiled).

This is exhibit #473 in "Why isn't Lisp dead yet? Isn't it older than dirt?".

Re:As long as we're limited to few characters... (1)

feijai (898706) | more than 8 years ago | (#13899800)

As usual, there already is a language that allows this, and (as usual) it's called Lisp. :-)
The unique specialness of an operator is that it may exist in a non-LL form, typically to provide infix notation. This is what makes an operator different from a function. But the defining feature of Lisp's syntax is that it is LL. It seems to me that by definition Lisp cannot support operator overloading. Sometimes Lisp is not the answer to any question foo.

Re:As long as we're limited to few characters... (1)

brpr (826904) | more than 8 years ago | (#13887876)

Haskell allows you to define new operators. It works very smoothly and makes it easy to implement concise domain specific languages. As another poster points out, Lisp also (sort of) has this feature, although this is more because it doesn't have infix operators at all. (Note to pedantic Lispkinks: yes, you could extend Lisp using reader macros etc. to add infix operators, but you really wouldn't want to, would you?)

Re:As long as we're limited to few characters... (1)

Fahrenheit 450 (765492) | more than 8 years ago | (#13888915)

Yeah. This is one of the things I'd like to see OCaml (my primary language of choice) steal from Haskell. It's got the ability to define new operators as well, but it's not nearly as flexible in that area as Haskell (without having to pull out the camlp4 hammer).

Meh. I really need to do more Haskell coding.

Blech (2, Insightful)

VGR (467274) | more than 8 years ago | (#13884254)

From the article:
a <=> b ..................... a.compareTo(b)

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.

Re:Blech (0)

Anonymous Coward | more than 8 years ago | (#13884508)

You hate us for our freedoms!

Re:Blech (1)

brpr (826904) | more than 8 years ago | (#13887901)

Yeah, that's a lot more readable.

Well yeah, actually, it is. Take a look at the kind of domain specific mini-languages that have been developed on top of Haskell and more recently C++. For example, the Spirit parser library for C++ which is part of Boost. Once you start composing complex expressions, infix operators are virtually required to make the end result anything close to readable. Haskell is a big win over C++ in this respect because (apart from all the advantages it has as a functional language) you can define new operators very easily.

Of course, if you're a Java hack[*] who likes to write programs in plodding imperative style (i.e. a sequence of simple statements), the benefits of being able to express complex structures simply will be lost on you. Pity.

[*]Not "hack" as in "hacker", you understand.

Java bans operator overloading? (3, Informative)

david.given (6740) | more than 8 years ago | (#13884653)

Well, yeah, except when it doesn't...
String a = "hello " + "world!";

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: [sysprog.net] 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.

Re:Java bans operator overloading? (1)

owlstead (636356) | more than 8 years ago | (#13885180)

Yes, that's the one exception. And one that one you should be very carefull with. Since Strings are immutable in Java, if you do "a" + "b" + "c", it will first create 3 Strings. Then it will add "a" and "b", creating a new String. Now *that* String will be formed into *another* new String by concatenating "c". That's quickly building up to the creation of a lot of String class instances. See "Effective Java" by Joshua Bloch.

The String is a pretty ugly hack, and the "+" operator should never have been used for it. Simply said, you are concatenating the Strings, not adding them up (for C++ fans, it's *not* the same as shifting a basicstring either.) The new java 1.5 provides the format and printf funtions which are much nicer. And the StringBuilder class has been around for a while, in case you really need to add up many String's.

Most of the time the concatenation is used for wrapping purposes anyway, and the language should have provided some sort of support for strings on multiple lines really.

Overloading of mathematical operators should only be available for instances that implement a certain interface, call it "Numeric" for instance. If it should be available at all. Note that not allowing operator overloading has the additional advantage of making very fast parsers. The new Java IDE's are all parsing as you type, so the Java language is really suited for this. Using this in .NET is just at its beginning, and it will be much harder to implement efficiently.

ps. Java developers: try this:

System.out.println("equal" == "equal");
System.out.println("eq" + "ual" == "equal");

Having fun yet?

Re:Java bans operator overloading? (1)

david.given (6740) | more than 8 years ago | (#13887634)

Yes, that's the one exception. And one that one you should be very carefull with. Since Strings are immutable in Java, if you do "a" + "b" + "c", it will first create 3 Strings. Then it will add "a" and "b", creating a new String. Now *that* String will be formed into *another* new String by concatenating "c". That's quickly building up to the creation of a lot of String class instances. See "Effective Java" by Joshua Bloch.

Except sometimes the compiler optimises this into creating a StringBuffer object, appending the Strings to it, and converting the StringBuffer back to a string once it's done... sometimes.

Having fun yet?

Grah.

What's the current state-of-the-art on actual good languages that compile into JVM byte-code?

Re:Java bans operator overloading? (1)

TummyX (84871) | more than 8 years ago | (#13905025)


Since Strings are immutable in Java, if you do "a" + "b" + "c", it will first create 3 Strings. Then it will add "a" and "b", creating a new String. Now *that* String will be formed into *another* new String by concatenating "c". That's quickly building up to the creation of a lot of String class instances. See "Effective Java" by Joshua Bloch.


Well actually, almost all java compilers would convert:

"a" + "b" + "c"

into "abc"

and "a" + s + "c"

into

new StringBuilder().Append("a").Append(s).Append("c"). ToString()


System.out.println("equal" == "equal");
System.out.println("eq" + "ual" == "equal");


That's pretty much one of the first things you learn about java. The == operator isn't overloaded for strings and const strings are interned.

Re:Java bans operator overloading? (1)

forkazoo (138186) | more than 8 years ago | (#13889378)

There does not now, nor will there ever, exist a programming language in which it is the least bit hard to write bad programs.

Shouldn't this be that no language makes it any harder to write bad code than to write good code? I mean, it seems to me that it really is quite hard to write a bad program (which does something useful) in Intercal, bf, or optimal IA64 ASM...

Oh, please. (1)

Black Parrot (19622) | more than 8 years ago | (#13884764)

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.

Re:Oh, please. (1)

owlstead (636356) | more than 8 years ago | (#13885273)

Back in the days, I could have endless discussions on C++ constructs. In C++ you can do almost anything, especially if you count in the preprocessor (and you have to, or #include won't work :). This makes for a very complex language. And although I miss the discussions, I am pretty glad I don't have to explain all this to the first new programmer that walks through the door. Because if it's there, people *ARE* going to use it. And even if you do understand it, the next programmer through the door won't understand a thing of it.

There is this lovely D language (there is, trust me). You can do almost anything in it. It's features as a language are endless - the author made a very, very long list. It should therefore never be used.

In Java, only basic types (and the ugly String concatenation) can be added up. Not very OO that, you should only be adding up "Numeric" objects, but that's a compromise. Other classes can't provide operator overloading, and I am very glad about that. If you are using many calculations with non-basic types, then these calculations will probably be part of your business logic. Calculate them in a language designed to do calculations, and then add them to your Java or .NET front-end.

Re:Oh, please. (1)

Haeleth (414428) | more than 8 years ago | (#13890369)

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.

Interestingly, there are languages that do this. OCaml, for example, uses "+" exclusively for integers; for floating-point numbers, "+." is used instead.

Now, OCaml's not a mainstream language, but it's reasonably popular as minor languages go. There's quite a few programmers out there who don't mind using a language that doesn't have any overloading. Evidently it's not quite as obvious as you think that overloading is automatically desirable...

Really bad examples (1)

owlstead (636356) | more than 8 years ago | (#13885370)

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.

Re:Really bad examples (1)

owlstead (636356) | more than 8 years ago | (#13885397)

Slashdot, don't try to be smarter than the author. If I want plain old text, *GIVE* me plain old text. That was obviously the "smaller than" operator I was talking about.

It's simple (0)

Anonymous Coward | more than 8 years ago | (#13887976)

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.

Security people will HATE you (1)

frantzen (137260) | more than 8 years ago | (#13888262)

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.

A safe way to provide operator overloading (1)

mrsbrisby (60242) | more than 8 years ago | (#13889129)

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 !=, ==, >, >=, &lt, &lt= 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.
Check for New Comments
Slashdot Login

Need an Account?

Forgot your password?
or Connect with...

Don't worry, we never post anything without your permission.

Submission Text Formatting Tips

We support a small subset of HTML, namely these tags:

  • b
  • i
  • p
  • br
  • a
  • ol
  • ul
  • li
  • dl
  • dt
  • dd
  • em
  • strong
  • tt
  • blockquote
  • div
  • quote
  • ecode

"ecode" can be used for code snippets, for example:

<ecode>    while(1) { do_something(); } </ecode>