Skip to main content

Operator overloading (again) and functions

131 replies [Last post]

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
hlovatt
Offline
Joined: 2003-11-18
Points: 0

I think operator overloading is difficult to do and current approaches from other languages are lacking, that is why so many people are against it. We need a fresh approach because operators are slightly different than normal methods in that they are related to each other and in general efficiency is a concern. Let me address efficiency first, you don't want:
[code]
r = a + b + c + d
[/code]
to be:
[code]
r = a.add(b).add(c).add(d)
[/code]
because each plus needs to make a new object (think Strings here). You want:
[code]
r = a + b + c + d
[/code]
to be something like:
[code]
final SomeType temp = a.toOperableForm();
temp.setAdd(b);
temp.setAdd(c);
temp.setAdd(d);
r = temp.fromOperableForm();
[/code]
This is how String behaves, with good reason! Therefore I suggest defining:
[code]
public interface AddOperator< T extends Addable > {
T toOperableForm(); /* makes a deep copy and can cast if required */
}
public interface Addable< T extends AddOperator > {
T fromOperableForm(); /* makes a deep copy */
void setAdd( T t ); /* changes the value by adding */
T unity(); /* returns unity (1) */
}
[/code]
Then a class that implements AddOperator can be used with operators +, +=, ++ (pre), and ++ (post) by transforming the code as shown above for +. String would therefore implement AddOperator and StringBuilder Addable. Some classes may implement both AddOperator and Addable.

Note how the user implements setAdd and unity; but all the operators +, +=, ++ (pre), and ++ (post) are defined in terms of just setAdd and unity, thus giving consistency between operations. This is the second problem with operator overloading addressed, i.e. when temp = a; temp + b != a += b

Similarly the interfaces:
[code]
interface ArithmeticOperators< T extends Arithmeticable > extends AddOperator< T > {
/* empty */
}
interface Arithmeticable< T extends ArithmeticOperators > extends Addable< T > {
void setDivide( T t );
void setMultiple( T t );
void setSubtract( T t );
}
[/code]
And a class that implemented ArithmeticOperators could be used with operators like AddOperator above but with /, *, and - as well as +, i.e. /=, *=, -=, etc.

Comparing is simpler than arithmetic because an intermediate class isn't needed because compare doesn't change any values:

[code]
public interface CompareOperators< T extends Comparable > extends Comparable< T >{ /* compatible with old code because it extends Comparable */
/* empty */
}
[/code]

Would allow <, >, !=, and == for a class that implemented CompareOperators. Currently, if you are implementing Comparable you shouldn't use == and equals should call compareTo. This solution elevates the problem of calling ==, but the problem of people forgetting equals remains (but is lessened since most people will use ==).

zander
Offline
Joined: 2003-06-13
Points: 0

> I think operator overloading is difficult to do and
> current approaches from other languages are lacking,
> that is why so many people are against it.

I'm against it because it makes you feel its more readable while in reality it is not.

An example I had from the C++ world not so long ago;
I have a list of objects that I fill with repetative calls to fetchAnswer(). The object returned from my method was pushed on the stack using an overloaded method that did a copy of the object.
All fine so far.
The problem started when we started to use a byte[] holding object which decided that operator= should not do a deep copy, like all the other objects, but to just reuse the byte[] instead.
We found out that each and every item on our list was actually reusing the exact same byte[] and our history was quite senseless.

Point is simple; allow developers to change the meaning of well defined operations and mistakes will start to happen in their usage.

hlovatt
Offline
Joined: 2003-11-18
Points: 0

I agree with your observation that there are many poor uses of operator overloading and your example is a good one. Another would be << and >> for io in C++. The specific issue that you mention of not deep copying is tackled in my proposal for AddOperator, the toOperableForm method and fromOperableForm methods provide the copying. Therefore I think that my proposal has addressed the issue that raise, which is a common issue with operators in C== because people forget to write some of them or think they are doing some clever optimization by not copying.

boubouzzzz
Offline
Joined: 2005-06-21
Points: 0

hello,

rediscover this page again :)

i don't speak english very well... i don't understand directly, and google is just a little my friend for this :)

zander, you think overload isn't good because you have bad experiences with reference knowledge.in fact, = never do a deep clone on a Object... it just assign the same reference... you have to surcharge clone() for deep cloning. the only automatic copy (I mean memory copy for the value) is for primitive types except array (that is a batard type, like autoboxing is), but including String (???).
I think you speak about : programers are stupid. things are too complex.

hlovatt, i'm agree with your point of view. but i think compiler need to transform this code to byte code... or native code...
when you use primitive types, copy of memory value is like copy of reference. autoboxing is here to make programers better life :) but the pity is that you can't have basic operation on it, and compiler don't take it as a primitive type. for autoboxing a lot of Integer Object are created...
We can have a reflexion about what the compiler can do on it, and how to make Java a full Object world.

for the one who don't what it at all, java can split in two languages : the office workers one, and the language.
(JVM can read both... -> byte code is the same, but compiler not)

did i never heard this ?

fuerte
Offline
Joined: 2004-11-22
Points: 0

Huh I was surprised to find this thread, after what I said independently on other threads. It seems that other people have come exactly to the same conclusion: Add operator overloading to fix autoboxing and == in Java.

ramimahdi
Offline
Joined: 2004-05-29
Points: 0

I think all the arguments againist operator overloading are all poll shits.
It is up to the programmer to know these tricks. Besides that, why don't we put a mechanism to specify the priority of operators.
I have once developed a programme in C++ for a pool game. It involved some Vectors calculations. The use of operator overloading made it really a piece of art code. the code was very readable.
I beleive the real reason that it is not yet available in java is that sun is willing to make such investment and pay for the cost.

boubouzzzz
Offline
Joined: 2005-06-21
Points: 0

bonjour,

In a first time, i will write in frensh, and after, try to traduce it...

bonjour,
j'ai cherché sur le forum 'operator' et je suis arrivé ici.
j'ai lu (compris?) le post.
ce qui me semble bizarre dans l'affaire, c'est que les primitives ne soit qu'un objet batard. Java 5 tente de corriger l'affaire avec l'autoboxing. largement plus gourmand que la manipulation de type primitif. donc, soit c'est une erreur comme j'ai cru comprendre dans un message et tout le monde l'admet comme pourri, soit java5 ne va pas au bout de la logique, et ne permet la surcharge d'operateurs.
pour eviter tout debat sur la forme ou l'ideologie, l'operateur defini en tant qu'objet (eh oui, le prerequis de java6 ;) ne s'applique qu'a une descendance ( une interface) d'object.
si l'operateur est defini comme objet, avec une syntaxe d'appel de methode differente (purement sur la forme...) , pani pwoblem pour le check a la compil :)
ca fais plaisir a ceux qui veulent pas culpabiliser des qu'ils passent par l'autoboxing.
ca fait plaisir a ceux qui lisent mieux les maths que les mots.
ca fait plaisir a ceux qui ecrivent des algorithmes pas pour de rire.
ca fait plaisir a ceux qui aime la secu a la compil.
ca fait plaisir a ceux qui aime connaitre la classe d'une variable dans une methode :)
ca fait plaisir a ceux qui croit que les concepts du C++ finiront par tous integrer java.
bon, ca fait pas plaisir a ceux qui vivent avec une ideologie...
et bon, faut prendre une decision pour .equals() ... mais c'est une major version ou pas ?

i will try to traduce it :)

hello,
i look for 'operator' on forum, i come here.
i read all the post (i hope i understand it)
what i feel strange is that primitive types aren't really Object. java5 try to correct this with autoboxing. but if autoboxing is good for primitive syntax why not going further and implements operator overloaded ?
'Operator' is defined as an Object, with different syntax when method is called, and can only be applied to a special Interface (implmented by Number for example). then, no problem to integrate it in compilator (just syntaxic review).
make happy people not happy with autoboxing.
make happy people reading better math than words.
make happy people writing a lot of algoritms.
make happy people who like compilation security.
make happy people who want to know variable class in a method :)
make happy people beliving C++ concept will finish to integrate java language.
make unhappy people loving granit on sand.
and people need to take decision for .equals() ... but it's a major, isn't it ?

gcfalc
Offline
Joined: 2005-02-04
Points: 0

I would agree with almost all of the "nay" sayers in this forum that operator overloading can be horribly abused. However, as a numerical programmer, I am very strongly in favor of operator overloading. Before I say anything else, please note that operator overloading has already been included in the new "Groovy" language which compiles on the JVM.

I have recently reverted to the Java language after a year excursion nito C# where not only are operator overloads available in force but other nifty ideas like implicit operator overloads. The clarity and elegance of formula coding with operator overloads is far superior to using syntactical things like "v.dot(w)" when you can use the simpler "v*w" by overloading the multiplication operator. Remember operator overloading is a syntactical clarifying concept as Gossling has pointed out in one of his papers.
As formulas and equations get more complicated, your code looks messier and messier and defect prone. With operator overloads your code almost reads like a math book!

But what numerical programmers really want is not the ability to create arbitrary sets of objects and operators for them, but to encapsulate the concept of a mathematical field. Simply said, you want to wheel and deal with a complex class, say it were called Complex, in exactly the same way you would deal with a type "double". They are both mathematical fields.

An alternative to enabling operator overriding, so excoriated and feared by the majority of people in this forum, might be the following (that would certainly make me happy):

Add three more primitives to the language with all field operations enabled. I would aslo include monomial operations such as square roots of complex numbers (using the appropriate branch) and th norm operator for a vector. They would be

[1] vector
[2] point
[3] complex

The reason for point and vector is as simple as the difference between affine space and a vector space. This idea is very important in the area of 3D graphics programming and animation.

I have never needed to overload any other kind of number type, but I would be interested in hearing about other people's ideas along these "new primitive" lines.

jwenting
Offline
Joined: 2003-12-02
Points: 0

you can create all 3 quite easily as a class, no need to create them as primitives...

If you want primitive-like behaviour of first class objects you should use C++ with large scale use of operator overloading.

gcfalc
Offline
Joined: 2005-02-04
Points: 0

Once again, my previous point was one of syntax and not one of how best to work with the limitations of the Java language. Perhaps an example will help me better explicate my viewpoint (and I am willing to wager also the majority of numerical programmers in the world):

This is a snippet from a method on a class that defines a type for an infinite plane. The method intersects two planes and returns the point of intersection (if it exists):

public Interaction intersect ( Plane m, Plane n, Point xP) {
...
Vector N1 = this.normal;
Vector N2 = m.normal;
Vector N3 = n.normal;
// double den = N1*(N2^N3); //with overloads
double den = dot(N1,cross(N2,N3));
Vector p1 = new Vector(this.origin);
Vector p2 = new Vector(m.origin);
Vector p3 = new Vector(n.origin);

double d1 = dot(N1,p1);
double d2 = dot(N2,p2);
double d3 = dot(N3,p3);

// Vector v = (1.0/den)*(d1*(N2^N3) + d2*(N3^N1) + d3*(N1^N2) ); (with overloads)
Vector v = add(scale(d1,cross(N2,N3)),add(scale(d2,cross(N3,N1)),scale(d3,cross(N1,N2))));
v = scale((1.0/den),v); (with member functions)

Here the lines that are commented out are using operator overloading (that is how you could do it in C# code). the add, scale, dot, and cross are static functions defined in the Vector class. If you are familiar with math notation, then ease of coding using the overloaded "*", "^" operators is obvious. By the way many books on vector advanced calculus actually use "^" to represent the vector product (cross)!

Look, operator overloading is not a big deal. Java is a very simple language ( I liken it to programming with crayons) and this should not become a bugaboo or taken in a religious context.

One last comment is that C#, which basically incorporated everything good about Java into its architecture and removed most of what was stupid in Java (the awkwardness and slowness of using primitives with the Collection classes for example), is now the superior language. When it incorporates its generic language structures, as Java has done in 1.5, it will be the best period. I left C# because I don't want to pay money to microsoft to use .NET in my work, not because I wanted to use Java again. I would NEVER have gone back to Java if I would have had to use Java 1.4.

The closer the syntax of a computer language is to the written language (the mathematical language in my case), the more we will have advanced the ball in the computer age.

-TRF

jwenting
Offline
Joined: 2003-12-02
Points: 0

no!

Or else add function pointers, heck add full pointer support (which is required for operator overloading anyway).

Add support for Java compilers to compile C++ code to Java bytecode.

Heck, change Java so C++ compilers can compile Java code into native code.

hmm, would be easiest to just change Java to be C++...

lucretius2
Offline
Joined: 2004-12-19
Points: 0

It's amazing how the topic of operator overloading generates so much heat (emotion/invective) and so little light.

Almost nobody seems to be able to get to the root of the 'problem', which is very simple.

Operators are just fancy syntax for method calls. (OK, for the built-in operators Java is mostly able to 'intrinsify' them into single bytecode instructions, but that's just an implementation detail. String's '+' operator is one example where an actual method call happens to be used).

The supposed 'problem' is: operators have an implied contract which a programmer writing an operator method has to obey. For instance, presumably the + and - operators should obey the rule a + b - b == a, otherwise their behaviour is confusing.

There is no new problem here. The above is just fancy syntax for the method calls a.plus(b).minus(b).equals(a). Methods in classes/interfaces have contracts. If you override the class/interface but disobey the contract, things screw up. Big deal. The fact that operators let you write '+' instead of 'plus' makes no difference - it's just another case where the programmer has to obey a contract when implementing a method.

Which leads me to the obvious way to implement operator overloading. The java.lang package should include a few interfaces which define methods like T plus(T), T multiply(T) etc. These methods have contracts, of course, defining the relationships between the various operators (e.g. a * 0 == 0).

The *only* special thing about these interfaces is that if your class implements one of them, Java would allow you to use the syntax a + b instead of a.plus(b). Of course, if you write a class containing a plus() method but without implementing the relevant interface, you are not bound by its contract, but then the compiler won't let you use the + syntax to call your method.

(There are some minor details which have simple solutions which I won't bore you with here, such as the fact that the built-in operators don't quite obey the rules of maths, due to overflow in integer arithmetic and loss of precision in floating point arithmetic; whether operators like =, !, == should be overridden; etc.)

'Problem' solved.

mthornton
Offline
Joined: 2003-06-10
Points: 0

The interfaces you suggest would probably for the maths concepts of Groups, Rings and Fields. So what are the types which satisfy (approximately) these axioms and might justify this special treatment:

complex, interval arithmetic, rational arithmetic, BigInteger, BigDecimal, matrices.

This could be covered by defining operator overloading for Number (and subclasses), ComplexFloat, ComplexDouble, ComplexNumber (complex with Number fields), and Matrices. I don't see the need for the more general interfaces (Group, Ring, Field).

Then most of the valuable uses of operator overloading are catered for without opening up the facility for abuse.

lucretius2
Offline
Joined: 2004-12-19
Points: 0

> The interfaces you suggest would probably for the
> maths concepts of Groups, Rings and Fields.

Yes that's exactly what I mean.

> Then most of the valuable uses of operator
> overloading are catered for without opening up the
> facility for abuse.

If you mean that operator overloading should only be allowed in certain classes supplied in the JDK, not in user-defined classes, I can only say: in what way would the latter be 'opening up the facility for abuse'? As I've said above, the only possible abuse is that a programmer breaks the contract of an operator method while overloading it. If this should be disallowed, then extending/implementing any class/interface should be disallowed. There is *absolutely nothing* special about operators: they are simply syntax sugar for regular method calls. (This is not rhetoric, it's a fact.)

> I don't see the need for the more general interfaces (Group, Ring, Field).

I can think of many uses which are not strictly mathematical. Points and vectors, colours and colour distances, musical pitches and intervals, currencies, exchange rates, dates and intervals between dates etc. are all things that can be added/subtracted, multiplied by scalars, and so on.

Code like the following might give you the shivers in C++ (has the programmer just devised 'cute' meanings for these operators?); in Java, you would be confident that the operators obey their contracts:

// Some hypothetical new date/time classes

CalendarDate date = new CalendarDate(); // today
date += 7; // a week from now

TimeOfDay time = new TimeOfDay(11,30); // 11.30 am
DateTime dt = date + time; // add 2 different types

TimeInterval ti = new TimeInterval(0,15); // 15 minutes
dt += ti * 2; // add 30 minutes
dt += new CalendarDate(); // compiler error: can't add a date to a date/time

mthornton
Offline
Joined: 2003-06-10
Points: 0

>
> I can think of many uses which are not strictly
> mathematical. Points and vectors, colours and colour
> distances, musical pitches and intervals, currencies,
> exchange rates, dates and intervals between dates
> etc. are all things that can be added/subtracted,
> multiplied by scalars, and so on.

Given the level of mathematical ignorance I see amongst programmers, some abuse of the contracts would be inevitable. For example, what interface would you use for Date? You shouldn't add two dates, and if you subtract them the result is a different type.

Points and vectors are special cases of matrices (which I did mention with some misgivings), and points in 2D are identical to complex numbers.

Currency calculations within a single currency is just a number (so £5 + £7 is easy), but what do we do with £4 + USD6? General currency values do NOT just add/subtract in a single well defined manner. In fact, as defined by my bank £4 + USD6 would probably leave me with a £10 overdraft!

lucretius2
Offline
Joined: 2004-12-19
Points: 0

> Currency calculations within a single currency is
> just a number (so £5 + £7 is easy), but what do we do
> with £4 + USD6? General currency values do NOT just
> add/subtract in a single well defined manner. In
> fact, as defined by my bank £4 + USD6 would probably
> leave me with a £10 overdraft!

Presumably you'd have a Sterling type and a Dollars type (subclasses of a Currency type), and you'd make plus() throw an exception if you tried adding a type that was incompatible.

BTW I didn't mention that these operator interfaces would be defined using generics, something like this:

interface Additive {
T plus(T);
T minus(T);
}

Some classes would want plus() to return a different type:
interface Additive {
U plus(T);
U minus(T);
}

Some would want to be able to add primitive types:
interface AdditiveDouble {
T plus(double d);
T minus(double d);
}

Clearly there are various details that need working out. There might be complications if you want to define a class (say, Complex) that has different add() methods to add different types. Because generics doesn't let you define 2 different methods add(T) and add(U) in the same class.

tackline
Offline
Joined: 2003-06-19
Points: 0

Seems as if we are creating a lot of interfaces here. We need an interface for each coherent set of operators. Probably with names that most programmers don't understand, like DivisionRing or SkewField. Adding primitives into the mix is worse.

Operations I would want to define (never redefine!) would include:

Rational + Rational -> Rational
Rational + int -> Rational
int + Rational -> Rational
int * Matrix -> Matrix
BigInteger + Rational -> Rational
Float + GaussianInteger -> Complex
Money + Money -> Money

I don't think interfaces cut it for operator overloading, although they may be useful in certain cases irrespective of operator overloading. You might just as well annotate a method to specify that it operator overloads. For non-final types, you'd probably also want to be able to annotate that no sub-type defines certain overloadings.

mthornton
Offline
Joined: 2003-06-10
Points: 0

> Seems as if we are creating a lot of interfaces here.
Yes too many to be viable. Given that unrestricted operator overloading is unlikely to ever be added to Java, I think all we can reasonably do is deal with the 90% case by implementing overloading just for Complex, BigInteger and BigDecimal. While it would be nice to allow it for user defined subclasses of Number, I suspect it may prove too difficult.

iwadasn
Offline
Joined: 2004-11-09
Points: 0

Please, not now, not ever. Here's the problem with operator overloading, and I have dealt with all these issues, they make code VERY easy to get VERY wrong.

what does this do: (--(++j))?
is it the same as: (++(--j))?, with most monkeys typing out overloaded operators, it isn't. The second one will often throw an exception (think iterators), and the first one can too.

How about this if(null == x), does that throw a null pointer exception? In lots of C# code it does, so there's no way to avoid the exception, a real mess.

I don't even dare ask about things like (x + y) * (y + z)
What does that do? Does it produce the same thing as xy + y^2 + xz + yz? Be careful, operators have VERY well defined meanings, and the whole purpose of overloading operators is so that you can do simple arithmatic with them (like that above), but this never works out well because people screw up their operators, and then simple math doesn't work in any sane way.

Please, NEVER have any more operator overloading than they already do.

dondi_imperial
Offline
Joined: 2004-11-22
Points: 0

This is the best argument I have ever heard against operator overloading. Though I was initially FOR adding op overloading to Java this argument has changed my opinion on this matter and I agree that we should NOT add it to Java unless someone can post a compelling rebuttal.

Dondi

kirillcool
Offline
Joined: 2004-11-17
Points: 0

The original proposal speaks for allowing overloaded operators in java.* and javax.* packages only. But what are those mysterious classes that really need this syntax (apart from BigDecimal, BigNumber and so on that are hardly ever used in a code that should be "easy to read" :( ).

If you want to allow overloading operators outside these packages, then you should probably go back to writing code in C++ and not try to import one of its ugliest features to Java. The amount of bugs caused by the mispropriate use of this feature may only be compared to misuse of macroes (do you want them too?).

Apart from pure mathematics (and Java is not trying to supplant Fortran's math libraries), the usage of 1-character mathematical signs instead of real names makes code much harder to understand:

Product p = element1 + element2;

or

Product p = element1.reactWith(element2);

The second form is much cleaner although it is slightly longer. Of course we can slide into a theoretical discussion that writing + really brings out the fact that the reaction takes two reagents (instead of element1 reacting "actively" with "passive" element2), but still operator + will be in this case called from element1. You might as well define class Reaction with

static Product react(Element el1, Element el2);

Can you provide some real examples (besides Big...) where the usage of operator overloading is clearly better than functions?

Kirill

andylarder
Offline
Joined: 2004-03-10
Points: 0

For doing maths with complex numbers, quaternions, vectors and matrices for starters.

kirillcool
Offline
Joined: 2004-11-17
Points: 0

As of now, Java has no complex numbers, vectors, matrices or quaternions in the core packages. But more important, is [b]+[/b] so much better than [b]mul[/b]? I don't think so. If you have matrix multiplication, does A*B look better than A.mul(B)? Not to me. It can be argued, of course, that having 5 matrics multiplication is awkward using [b]mul[/b]. But i'm afraid there are very few real-life algorithms that need to multiply 5 matrics in a single step. More complex linear algebra algorithms involve transposition or inverse, but i guess you wouldn't propose something like A^(-1) where A is a matrix to the core language.

mthornton
Offline
Joined: 2003-06-10
Points: 0

The justification for operator overriding is at its best with Complex, for in this case there are many complicated expressions which do indeed look much better with infix operators. Examples can be found in many engineering text books.

dondi_imperial
Offline
Joined: 2004-11-22
Points: 0

+1 for operator overloading. I feel this will allow users of Java to work with "non-primitives" as they would with primitives. This along with auto (un)boxing and generics will allow us to write code that is more generic therefore more reusable.

I think the reason that there are some who don't want to see features like operator overloading in java is that it increases the possibility of someone writing something dumb (unintuitive) like Object + Object. I don't see this as a reason for those of us that do know how to make use of these features to live without them.

Dondi

kcpeppe
Offline
Joined: 2003-06-15
Points: 0

> +1 for operator overloading. I feel this will allow
> users of Java to work with "non-primitives" as they
> would with primitives. This along with auto
> (un)boxing and generics will allow us to write code
> that is more generic therefore more reusable.

Humm, operator overload is really a C++isum that comes from the notion that certian symbols are embedded in the langauge to support intrinsic functions. This syntact puts the notion of intrinsics right in your face. I would suggest that the problem is not that there are intrinsics, it is just that the syntax has been set to point this out. At this point, to expand the set of characters one can use to support naming methods looks ugly. The other option is to allow "primitive" style syntax with objects which is confusing (any other options aside from restriction of packages which would have the effect of blurring the line between libraries and language). Normalizing the syntax between objects and primitives (as Smalltalk does with direct objects) is basicaly rewritting the langauge (i.e. you get a new one) so it would seem that the best option is to maintain status quo.

>
> I think the reason that there are some who don't want
> to see features like operator overloading in java is
> that it increases the possibility of someone writing
> something dumb (unintuitive) like Object + Object. I
> don't see this as a reason for those of us that do
> know how to make use of these features to live
> without them.

This is an interesting argument that I would use against the introduction of generics. :)

We already know that autoboxing is a dog.

Interestingly enough, I get the feeling that some of these features were in response to C#. To that I answer, read iCringely's (http://www.pbs.org/cringely/) piece on how to complete with MS, ignore them!

markswanson
Offline
Joined: 2003-06-11
Points: 0

> Add operator overloading ...

NO!!!

mgrev
Offline
Joined: 2003-08-12
Points: 0

Why are you wasting time on operator overloading?

It's pretty clear that Sun will *never* add it. Graham and gang have said more than once something like: We're open to suggestions though operator overloading is probably out of the question.

I concurr.

public static final boolean OPERATOR_OVERLOADING = false;

Live with it.

:)

Cheers,
Mikael Grev

kcpeppe
Offline
Joined: 2003-06-15
Points: 0

> Why are you wasting time on operator overloading?
>

What is operator overloading? What is an operators? I believe that it is important to understand what these things are so we can ask the real question.

If operator overloading means let us expand the allowable characters that can be used to define function names, then the question is, what would that really buy us? Maybe we could define something like;

ImaginaryNumber a, b, c;
....
// Current object message send syntax
a = b.+(c);

// Current primitive message send syntax
a = b + c;

The problem with the first is that it's ugly. The problem with the second is that it mixes what is current two distinct sytaxtic patterns in the langauge, that meant for objects and that meant for primitives. The problem with mixing syntax like this is that now I've less information. Are a, b and c primitives or are they objects.

I would agree that expanding the allowable characters that could be used to define messages would be good but only if can promote primitives to first class status and eliminate the '.' to normalize the syntax seperating primitives from objects. But, if we did all this, we'd be working with a different langauge now wouldn't we. ;)

joergwassmer
Offline
Joined: 2004-09-20
Points: 0

I made the experience that operator overloading makes code MUCH harder to read, harder to understand, and much more error prone (C++).

In detail: I'm full of hope that Java will never make that weird stuff possible. It already was a mistake to implement the operator overloading for the Java primitive type wrappers (">" and "<" compares values, but "==" compares identities. Latter has to be like it is - but try to explain it to people who are not familiar with Java).

patrikbeno
Offline
Joined: 2004-10-11
Points: 0

> Add a "function" keyword modifier to methods that
> means that the method has no side effects.

And how do you want to guarantee that 'function' does not have any side effects? Function can only read anything? It can call another functions, but not standard methods (procedures)?
As I understand this, this would impose strong limitations on the 'functions', making them suitable only for small and simple things.
It is not worth introducing new keyword that may break backward compatibility.

Anyway, if you elaborate more on reasons why we need that and propose a sound solution, we can still use annotation for this.

your turn :-)