|
Replies:
131
-
Last Post:
Jan 9, 2009 7:48 PM
by: celticminstrel
|
Threads:
[
Previous
|
Next
]
|
|
|
|
|
|
Operator overloading (again) and functions
Posted:
Nov 6, 2004 6:19 AM
|
|
|
Add operator overloading to Java but make it only usable within the java.* and javax.* package hierarchies. This would allow complex, interval arithmetic, matrix and vectors, etc. to be added. It would allow JCP JSRs to add well thought out operators while not allowing the abuse that making the facility available to everyone would lead to.
Add a "function" keyword modifier to methods that means that the method has no side effects. This has most of the advantages of "const" modifiers to methods and their parameters while being very simple.
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 6, 2004 7:34 AM
in response to: m_r_atkinson
|
|
|
> 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
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 17, 2004 5:29 PM
in response to: m_r_atkinson
|
|
|
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 ""
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 18, 2004 1:45 AM
in response to: m_r_atkinson
|
|
|
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
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 21, 2004 2:39 AM
in response to: mgrev
|
|
|
> 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.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 22, 2004 5:35 AM
in response to: mgrev
|
|
|
While user defined operator overloading is unlikely, I think there is a reasonable case for adding a couple of extra classes (Complex with float and double forms), for which the appropriate operators were overloaded.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Dec 30, 2004 8:20 AM
in response to: mgrev
|
|
|
Java has a big problem which will always prevent op overloading. In C++, the == op is undefined by default whereas in Java, it is well defined.
This has already introduced potential bugs in autoboxing:
int a = 1001;
Integer b = a;
a b is false but a == b is false.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Dec 30, 2004 10:35 AM
in response to: arae
|
|
|
Um... but under your above logic a == b is true. since a is an int, and b is an Integer, b is unboxed in order to perform the == operations. That being said: int a = 1001; Integer b = a; Integer c = a; b == c is false.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Jan 5, 2005 6:24 AM
in response to: subanark
|
|
|
> Um... > but under your above logic a == b is true. > since a is an int, and b is an Integer, b is unboxed > in order to perform the == operations. > That being said: > int a = 1001; > Integer b = a; > Integer c = a; > b == c is false.
Which sort of proves my point. Autoboxing has already made the == op ambiguous and that will be a source of bugs, errors and reduced maintainability.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Oct 25, 2005 11:50 AM
in response to: arae
|
|
|
> > Um... > > but under your above logic a == b is true. > > since a is an int, and b is an Integer, b is > unboxed > > in order to perform the == operations. > > That being said: > > int a = 1001; > > Integer b = a; > > Integer c = a; > > b == c is false. > > Which sort of proves my point. Autoboxing has already > made the == op ambiguous and that will be a source of > bugs, errors and reduced maintainability.
I'm no fan of Autoboxing but in this case it works as it should or as best it can. Don't forget there is a difference between deep and shallow equality. All this example is doing is pointing that out.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 4, 2005 2:44 PM
in response to: kcpeppe
|
|
|
if it makes your code ambiguous then just don't use it. Leave it to the others who need it.
Many people are doing applications concerned with calculations. So have operator overloading will provide great clarity to their programs.
You say it makes it ambiguous because your programming buisiness didn't need it. So simply stay behind and don't put your nose in this discussion. If it became a feature in java, just don't use.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 7, 2005 12:13 AM
in response to: ramimahdi
|
|
|
operator overloading never adds clarity. All it ever does is make code harder to understand by enabling people to write operators that have no relation at all with the mathematical representation of what that operator is normally expected to do.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 7, 2005 3:51 AM
in response to: jwenting
|
|
|
> operator overloading never adds clarity.
Should we be using separate operators for integers and floating point? If operator overloading makes sense for these types, then it should also be appropriate for complex numbers. I would happily agree that overloading should be restricted to the basic mathematical operations.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 7, 2005 11:20 AM
in response to: jwenting
|
|
|
> operator overloading never adds clarity.
Yeah right.
a = new StringBuilder(new String({'a', 'b', 'c'})).append(new String({'d', 'e'}));
or
a = "abc" + "de";
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 7, 2005 11:30 AM
in response to: fuerte
|
|
|
> > operator overloading never adds clarity. > > Yeah right. > > a = new StringBuilder(new String({'a', 'b',
> 'c'})).append(new String({'d', 'e'}));
>
edge case...
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 7, 2005 12:04 PM
in response to: kcpeppe
|
|
|
String concatenation should have had an operator of its own, '$' perhaps, rather than overloading +.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 7, 2005 4:00 PM
in response to: kcpeppe
|
|
|
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:
r = a + b + c + d
to be:
r = a.add(b).add(c).add(d)
because each plus needs to make a new object (think Strings here). You want:
r = a + b + c + d
to be something like:
final SomeType temp = a.toOperableForm();
temp.setAdd(b);
temp.setAdd(c);
temp.setAdd(d);
r = temp.fromOperableForm();
This is how String behaves, with good reason! Therefore I suggest defining:
interface AddOperator< AO extends AddOperator< AO, A >, A extends Addable< AO, A > > {
A toOperableForm(); /* makes a deep copy and can cast if required */
}
interface Addable< AO extends AddOperator< AO, A >, A extends Addable< AO, A > > {
AO fromOperableForm(); /* makes a deep copy */
void setAdd( AO t ); /* changes the value by adding an AddOperator */
void setAdd( A t ); /* changes the value by adding an Addable */
A unity(); /* returns unity (1) */
}
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:
interface ArithmeticOperators< AO extends ArithmeticOperators< AO, A >, A extends Arithmeticable< AO, A > > extends AddOperator< AO, A > {
/* empty */
}
interface Arithmeticable< AO extends ArithmeticOperators< AO, A >, A extends Arithmeticable< AO, A > > extends Addable< AO, A > {
void setDivide( AO t );
void setMultiple( AO t );
void setSubtract( AO t );
void setDivide( A t );
void setMultiple( A t );
void setSubtract( A t );
}
And a class that implemented ArithmeticOperators can not only be used with + operators, like AddOperator above, but also 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:
public interface CompareOperators< T extends Comparable > extends Comparable< T >{ /* compatible with old code because it extends Comparable */
/* empty */
}
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 ==).
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 8, 2005 12:02 AM
in response to: fuerte
|
|
|
The usual case of course is people overloading operators to add DoodAds to DoDos and using the multiplication operator to do it.
So you get operators working on disparate datatypes and doing things that even if they were the same datatype would not be what you'd expect them to do.
Language designers are usually more sensible than our average esteemed colleagues/competitors in the marketplace.
And as there's no way to ensure at compiler level that an overloaded operator actually does a mathematically correct job there's no way to protect people from themselves and each other when using operator overloading. As Java is designed to protect the programmer from the more common mistakes made by C++ and other language users this is a Bad Thing, as operator overloading is among the more frequently abused features of languages like C++.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 8, 2005 1:05 AM
in response to: jwenting
|
|
|
@jwenting
See post immediately above yours. I think this addresses your concerns.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 8, 2005 1:06 AM
in response to: jwenting
|
|
|
There is little dispute that overloading in C++ has been grossly abused. However that is quite different to saying that "overloading never adds clarity" because in some carefully restricted cases it clearly does.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 7, 2005 1:45 AM
in response to: ramimahdi
|
|
|
> > You say it makes it ambiguous because your > programming buisiness didn't need it. So simply stay > behind and don't put your nose in this discussion. If > it became a feature in java, just don't use.
What my business is in this forum is to add to the discussions based on my experiences and education with computer languages. Operator overloading is a artifact of having operators in the language. IMHO a better direction is to remove operators from the langauge.
That said, it is not going to happen in Java, nor would I want it to for arguments that I've made in other threads in this forum. "==" and "=" both have a clear function. They are notationally clean. If you were to confuse the meaning of "=" you will produce code that is difficult for me to read. So it doesn't matter is I use it or not because others will.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Dec 30, 2004 11:12 AM
in response to: arae
|
|
|
That's easy: don't allow overloading of ==.
Auto-unboxing does not, as far as I am aware, introduce bugs into existing pre-1.5 source.
javac probably should give a warning if you try == on Integers, Strings and similar. Particularly if there was a method <T>boolean identityEquals(T,T) added to System.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 20, 2004 6:50 PM
in response to: m_r_atkinson
|
|
|
> Add operator overloading ...
NO!!!
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 21, 2004 6:22 AM
in response to: m_r_atkinson
|
|
|
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
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 22, 2004 3:58 AM
in response to: kirillcool
|
|
|
For doing maths with complex numbers, quaternions, vectors and matrices for starters.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 22, 2004 4:35 AM
in response to: andylarder
|
|
|
As of now, Java has no complex numbers, vectors, matrices or quaternions in the core packages. But more important, is + so much better than mul? 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 mul. 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.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 22, 2004 5:31 AM
in response to: kirillcool
|
|
|
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.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 22, 2004 7:23 PM
in response to: mthornton
|
|
|
+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
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 22, 2004 11:40 PM
in response to: dondi_imperial
|
|
|
> +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!
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Dec 19, 2004 2:37 PM
in response to: m_r_atkinson
|
|
|
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.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Dec 19, 2004 7:40 PM
in response to: iwadasn
|
|
|
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
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Dec 20, 2004 2:59 AM
in response to: iwadasn
|
|
|
> 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?
Those expressions can already produce different results with double and float values!
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Feb 4, 2005 2:48 PM
in response to: iwadasn
|
|
|
> 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.
Operator overloading follows a very well defined set of semantics. What would your code above look like without overloaded operators, and how do I learn the semantics of your naming convention.
j.preIncrement().preDecrement(); j.preDecrement().preIncrement();
> > 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)
x.plus(y).times(y.plus(z))
How do I know that the function called plus actually follows the same semantics as + ?
Operator overloading defines a very clear set of semantics that can be reviewed against these semantics.
> 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.
Please allow syntax that carries a very well defined semantics that matches the domain of scientific programming.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Dec 20, 2004 2:56 AM
in response to: m_r_atkinson
|
|
|
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++...
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Dec 20, 2004 4:36 AM
in response to: jwenting
|
|
|
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.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Dec 20, 2004 5:48 AM
in response to: lucretius2
|
|
|
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.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Dec 20, 2004 6:22 AM
in response to: mthornton
|
|
|
> 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
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Dec 20, 2004 7:06 AM
in response to: lucretius2
|
|
|
> > 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!
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Dec 20, 2004 7:54 AM
in response to: mthornton
|
|
|
> 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> { T plus(T); T minus(T); }
Some classes would want plus() to return a different type: interface Additive<T,U> { U plus(T); U minus(T); }
Some would want to be able to add primitive types: interface AdditiveDouble<T> { 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.
|
|
|
|
|
|
|
|
Operator overloading interface explosion
Posted:
Dec 21, 2004 3:28 AM
in response to: lucretius2
|
|
|
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<UKP> + Money<UKP> -> Money<UKP>
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.
|
|
|
|
|
|
|
|
Re: Operator overloading interface explosion
Posted:
Dec 21, 2004 4:37 AM
in response to: tackline
|
|
|
> 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.
|
|
|
|
|
|
|
|
Re: Operator overloading interface explosion
Posted:
Dec 21, 2004 5:57 AM
in response to: tackline
|
|
|
> 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.
There are ways round this. We could, as you say, have a few interfaces which contain a group of operator methods. E.g. maybe all the plus() and minus() methods, including plus(T), plus(double), plus(int), etc., could go in the same interface. If you don't want to implement some of them for a particular class, make them throw UndefinedOperationException. This is the same approach used in the Collections framework of course.
A slightly more fine-grained approach would be, say, to have an Addable interface which contains plus(T) and minus(T), then a subinterface AddablePrimitive which adds plus(int), minus(int), plus(double), minus(double) etc. This helps with the common case of a class which only lets you add objects of its own type, e.g. classes representing units (SI units, cows, maybe currency, etc.).
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Dec 23, 2004 12:25 AM
in response to: lucretius2
|
|
|
C++ style operator overloading allows pretty much any behaviour to be defined for pretty much anything...
You loose any hint of predictable behaviour that way.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Feb 4, 2005 2:35 PM
in response to: jwenting
|
|
|
> C++ style operator overloading allows pretty much any > behaviour to be defined for pretty much anything... > > You loose any hint of predictable behaviour that way.
Doesn't this hold true if you overload hash() or equals() in Java?
how is myObject.equals(myOtherObject) in java any less risky the myObject == myOtherObject in C++?
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Dec 28, 2004 9:22 AM
in response to: lucretius2
|
|
|
Operator overloading was very simple in Smalltalk.. because Smalltalk was a simple language and operators where used for mathematical things.
In C++ (STL) the whole notion was completely and utterly abused. In a misguided attempt to make syntax concise they used it for iteration and other non-intuitive purposes which made the whole thing the horrible mess it is today (thank God Java came around and saved me from it).
Operator overloading should only be used by experts to create mathematical classes (like BigDecimal, Complex, or Matrix or whatever).
Unfortunately since lots of us Java programmers where brain damaged by C++.. I'd have to say that I'm against this feature. That is, unless it is added with the caveat that any application programmer that uses it will be taken out and shot! (Mathematical library developers are the only ones that need it.. but even they should be held to a high standard)
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Dec 28, 2004 9:57 AM
in response to: dog
|
|
|
> Operator overloading should only be used by experts > to create mathematical classes (like BigDecimal, > Complex, or Matrix or whatever).
Ah, this old argument again.
Would you also say that 'implementing an interface should only be used by experts'?
If not, in what way would you say that operator overloading is not simply an alternative syntax for implementing an interface? (The interface being a set of methods called '+', '-' etc., whose contracts are whatever mathematical axioms they need to behave in a roughly number-like way.)
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Feb 4, 2005 2:37 PM
in response to: dog
|
|
|
> > Operator overloading should only be used by experts > to create mathematical classes (like BigDecimal, > Complex, or Matrix or whatever). > > Unfortunately since lots of us Java programmers where > brain damaged by C++.. I'd have to say that I'm > against this feature. That is, unless it is added > with the caveat that any application programmer that > uses it will be taken out and shot! (Mathematical > library developers are the only ones that need it.. > but even they should be held to a high standard)
Scientific programming would be much easier in java if operator overloading was implemented. Why should you have to go to C# if you want to write clean high-level math libraries?
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Feb 4, 2005 3:12 PM
in response to: m_r_atkinson
|
|
|
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.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Feb 8, 2005 1:48 AM
in response to: gcfalc
|
|
|
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.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Feb 8, 2005 3:31 AM
in response to: jwenting
|
|
|
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
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Jun 21, 2005 8:07 PM
in response to: m_r_atkinson
|
|
|
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 ?
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Jun 22, 2005 2:23 AM
in response to: m_r_atkinson
|
|
|
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:
r = a + b + c + d
to be:
r = a.add(b).add(c).add(d)
because each plus needs to make a new object (think Strings here). You want:
r = a + b + c + d
to be something like:
final SomeType temp = a.toOperableForm();
temp.setAdd(b);
temp.setAdd(c);
temp.setAdd(d);
r = temp.fromOperableForm();
This is how String behaves, with good reason! Therefore I suggest defining:
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) */
}
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:
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 );
}
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:
public interface CompareOperators< T extends Comparable > extends Comparable< T >{ /* compatible with old code because it extends Comparable */
/* empty */
}
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 ==).
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Jun 22, 2005 6:02 AM
in response to: hlovatt
|
|
|
> 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.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Jun 26, 2005 6:31 PM
in response to: zander
|
|
|
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.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Aug 20, 2005 7:52 PM
in response to: hlovatt
|
|
|
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 ?
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Aug 26, 2005 5:33 AM
in response to: boubouzzzz
|
|
|
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.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Oct 25, 2005 9:43 AM
in response to: fuerte
|
|
|
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.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 21, 2005 10:35 PM
in response to: m_r_atkinson
|
|
|
The technical details of how it could be implemented internally are interesting but not really relevant to the discussion.
Operator overloading definitely should be added. Those who don't like it are free not to use it. There was a similar debate against generics when this was proposed.
Most of the arguments against operator overloading are flawed - in most cases the exact same arguments would apply equally to functions. Sure, an idiot might use the * operator to add instead of multiply, but wouldn't such an idiot create a function called "multiply(X)" in such circumstances? Couldn't such an idiot create a function called "equals" to alter the contents of an object? If we're going to withhold functionality from Java just because there are idiots out there then might as well return to pencil and paper.
Operator overloading greatly increases readability. If used improperly it can have as detrimental an effect as using any other language feature improperly. If I have a class called "Money" which combines a currency with an amount, I'd much rather have an operator+ which adds two instances, throwing an exception if they don't have the same currency, or multiplies an instance with a primitive number, than try to read through a long line of .multiply(X).minus(Y).divide(Z)... The reason it improves readability is that some objects are logically associated with adding, subtraction and so on. I can add physical money, so why not an object that represents it?
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 22, 2005 1:19 AM
in response to: rcasha
|
|
|
No, you're NOT free not to use it. 90% of programming consists of the maintenance and use of code created by others, and if those others abuse it you're stuck with having to maintain their code.
Generics are open to abuse, but not by far to the extent that operator overloading is.
And no, limiting OO to just a few specific cases won't help. That will just open the floodgates to people screaming bloody murder that it's not allowed for their specific pet case and demanding it is expanded again and again in further releases until it is as generic as in C++. There would still be no checks and ballances to make sure it can't be abused (and if those existed people would complain about that) as the compiler can't possibly know whether something is mathematically correct for complex objects (and for simple cases involving things like Integer and Double it's effectively already implemented through autoboxing).
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 22, 2005 4:00 AM
in response to: rcasha
|
|
|
> Sure, an idiot might use the * operator to add > instead of multiply, but wouldn't such an idiot > create a function called "multiply(X)" in such > circumstances? Couldn't such an idiot create a > function called "equals" to alter the contents > of an object?
That doesn't seem to be happening in reality though. Programmers do use overloading for cutesy tricks; they do not seem to use random names to perform unrelated operations. Theory vs reality.
What does happen in reality is people overloading << to perform output. + to insert an object to a collection or a window to a frame. / Operator overloading greatly increases readability.
Experience with C++ shows it is more often used to decrease readability.
> try to read through a long line of .multiply(X).minus(Y).divide(Z)
With experience from sin(), sqrt(), etc in mathematical software I find that the use of temporary variables enhances readability of such long lines. Just like with any long list of method calls. Even when using operators I tend to break long lines of A+(B/C)*D<<(E&F-G) with temporaries when it enhances readability.
Why are some people concerned with long lines of mathematical method calls but not with long lines of .append(W).substring(X).toString(Y).charAt(Z)? Do you actually have mathematical software with such long lines? Have you tried temporary variables?
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 22, 2005 9:45 AM
in response to: rcasha
|
|
|
> The technical details of how it could be implemented > internally are interesting but not really relevant to > the discussion.
Of course those details are important to the discussion because they don't come for free, they will impact other features, etc.
> Operator overloading definitely should be added. > Those who don't like it are free not to use it. There > was a similar debate against generics when this was > proposed.
Bah! That sort of psuedo-logic is an great example of exactly the problem with so much of the thinking around operator-overloading -- completely ignoring the real, "unintended" consequences isn't logic, it's wishful thinking. Of course the simplistic examples are seductively useful (e.g., Java's support of overloading + for strings) but the consequences even with those simplistic examples are arguable (as discussed in other messages in this thread). Trying to extend the simplistic rationalization for op-overloading to the general case, for a language like Java, is just plain nuts.
Operator overloading erodes the ability for people to be able to look at the code and understand what's going on. The history of the abuses of op-overloading is overwhelmingly clear that the resulting ambiguity leads to ridiculous amounts of confusion and bugs.
Even in the very best cases (i.e., complex math) the increased density of expression costs a lot in terms of collateral damage when implemented as part of generalized op-overloading in a general purpose programming language like Java (one need look no further than the festering cesspool that is op-overloading in C++). [The analogy here is the same as how logging is the only easy, obviously useful example of AOP. :-)] It would be much better (easier, safer, etc.) to just bake in the op-overloading support for a slew of math stuff (BigInteger, BigDecimal, vector/matrix math, etc.) than it would be to add the general op-overloading capabilities. At least that way, the potential confusion over what's going on is constrained.
Java, whether we like it or not, has already been framed along certain lines. That is, the design of the language "thinks" a certain way and that matters to everyone who uses it. Rather than trying to constantly morph it with everybody's pet features, if you really have a problem that would benefit so greatly from that feature, why don't you create a language that expresses exactly what you want? There are plenty of examples that you can start with that even target the JVM so your little language (aka "domain specific language") would be completely interoperable with your Java code.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 22, 2005 1:22 PM
in response to: johnm
|
|
|
> Operator overloading erodes the ability for people to > be able to look at the code and understand what's > going on. The history of the abuses of op-overloading > is overwhelmingly clear that the resulting ambiguity > leads to ridiculous amounts of confusion and bugs.
If one were to discount C++ as an aberation are there any other examples of serious abuse? Mathematicians, after all, have been overloading operators to reasonable effect for quite a while.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 22, 2005 2:31 PM
in response to: mthornton
|
|
|
> If one were to discount C++ as an aberation are there > any other examples of serious abuse? Mathematicians, > after all, have been overloading operators to > reasonable effect for quite a while.
Haskell - in Haskell you can have any sequence of symbols and use them infix so you get stuff like:
addA :: Arrow a => a b Int -> a b Int -> a b Int
addA f g = proc x -> do
y <- f -< x
z <- g -< x
returnA -< y + z
addA f g = arr (\ x -> (x, x) >>>
first f >>> arr (\ (y, x) -> (x, y)) >>>
first g >>> arr (\ (z, y) -> y + z))
addA f g = f &&& g >>> arr (\ (y, z) -> y + z)
The first line above defines the types of the inputs and outputs to a function called addA. The next three sections are all different ways defining addA. addA takes two functions and a value as its input, applies both functions to the value and sums the results from the functions. The first definition is probably the clearest, f and g are the functions and x is the value. But the first definition is cheating because it also has some syntatic sugar in it as well as operators.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 23, 2005 5:06 AM
in response to: mthornton
|
|
|
> Mathematicians, after all, have been overloading > operators to reasonable effect for quite a while.
It is a rare mathematician who discovers a new mathematical entity and creates a new notation for it. When he does it may well be the high point of his career, so he is likely to be careful about it. And peer review will work to weed out any obviously dumb ideas.
A junior programmer can whip up a couple of classes and a dozen methods before lunch.
Maybe us programmers are just more frequently presented with the opportunity to be cute. And, alas, too often the temptation overpowers us.
|
|
|
|
|
|
|
|
Discounting C++
Posted:
Nov 23, 2005 10:16 AM
in response to: mthornton
|
|
|
> If one were to discount C++ as an aberation are there > any other examples of serious abuse? Mathematicians, > after all, have been overloading operators to > reasonable effect for quite a while.
(A) Other than as some theoretical exercise, we cannot discount the lessons of C++ because Java and the Java community are all too similar to the C++ world in nearly all facets/dimensions. It feels like deja vu all over again.
(B) Other folks have already mentioned some other general purpose programming languages which were more coherently designed, from the ground up, to support operator overloading. First off, note how none of those languages have become popular (for good and bad reasons, timing, etc.). Second, note how those languages have pretty rabid followings amongst programmers working on certain kinds of problems (where the strengths of those languages can manifest themselves). Thirdly, look at all of the abuses done with other, similar features such as the C preprocessor and Lisp macros, "annotations" in Java 5, and AOP.
(C) As I noted, math is one place where op-overloading really does seem to provide enough bang for the buck. A large part of that is because math has a lot of reasonably well defined, disciplined constraints. Alas, adding generalized support for op-ov means there's basically no constraints on the hells that programmers can create. Personally, I would much rather see a fully supported, high-end math system added to Java with operator overloading.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 22, 2005 9:55 PM
in response to: johnm
|
|
|
Many who disagree with operator overloading keep quoting the example of C++. It's true that oo in C++ was messed up, and I think it's mainly because of the way the C++ libraries like the stream io libraries were implemented: C++ itself set the stage for this wholesale abuse of oo by using the left-shift and right-shift operators for I/O. It followed naturally that there would be other cases of oo abuse from others.
That does not have to be the case with Java. Like I said, operator overloading can be abused just like any other language feature. However if Java starts the ball rolling by implementing oo functionality and adding it to all Number classes and other objects which lend themselves to the concept of being added/subtracted etc., history need not repeat itself.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 22, 2005 10:08 PM
in response to: rcasha
|
|
|
> Many who disagree with operator overloading keep > quoting the example of C++. It's true that oo in C++ > was messed up, and I think it's mainly because of the > way the C++ libraries like the stream io libraries > were implemented:
OO in C++ is messed up because the langauge *has* operators! It has operators because not everything is an object. This means that you have strange things like if-then-else, switch and while statements. You have other very strange things like public final static class Math (oops that is in Java). IOWs you have a mix of first and second class citizens in the language. This is why it's messed up. To continue down that path is to mess it up even more. Why not back trace and work to make the second class citizens first class one?
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 23, 2005 4:53 AM
in response to: kcpeppe
|
|
|
> Why not back trace and work to make the second > class citizens first class one?
There already are a number of "pure" OO languages. If you need one, surely google will find one for you! No need to try to turn every language in the world into Eiffel.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 23, 2005 6:46 AM
in response to: sjasja
|
|
|
> > Why not back trace and work to make the second > > class citizens first class one? > > There already are a number of "pure" OO languages. If > you need one, surely google will find one for you! No > need to try to turn every language in the world into > Eiffel.
Why do we have to turn Java into C++ or C#?
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 28, 2005 12:00 AM
in response to: kcpeppe
|
|
|
> > > Why not back trace and work to make the second > > > class citizens first class one? > > > > There already are a number of "pure" OO languages. > If > > you need one, surely google will find one for you! > No > > need to try to turn every language in the world > into > > Eiffel. > > Why do we have to turn Java into C++ or C#?
Wiser words have rarely been uttered! Answer: we don't. But there's a lot of kiddos who do seem to think that just because X (where X is any programming language of their liking) has feature Y (where Y is any feature they particularly like in language X) that Java should have that exact same feature as well and preferably using the same syntax. More often than not the marketing types at Sun headquarters then order the language development team to find a way to include that feature because it supposedly would make Java more interesting to users of language X and thus increase its market share.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 28, 2005 6:52 AM
in response to: jwenting
|
|
|
> More often than not the marketing types at Sun > headquarters then order the language development team > to find a way to include that feature because it > supposedly would make Java more interesting to users > of language X and thus increase its market share.
Really?
The language feature that I can think that could apply to is auto *un*boxing. Possibly the exact form of varargs. In the library there is printf. I can't think of anything else your statement could apply to. I think you made it up.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 23, 2005 4:04 AM
in response to: rcasha
|
|
|
doesn´t matter..
What we will gain with operator overloading ?
what is the difference between to write:
A + B; A.plus(B);
just a few letters :))
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 23, 2005 4:17 AM
in response to: felipegaucho
|
|
|
Try some of the more complex expressions involving complex variables that arise in electrical engineering for example. Too many additional characters (and especially parentheses) and the expression becomes unrecognisable. If you use temporary variables to spread the expression over too many lines then the amount of code you can easily see on a page/screen goes down. This again damages comprehension.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 23, 2005 4:48 AM
in response to: mthornton
|
|
|
> Try some of the more complex expressions involving > complex variables that arise in electrical > engineering for example. Too many additional > characters (and especially parentheses) and the > expression becomes unrecognisable.
I have worked with electricity distribution network analysis software written in C. It wasn't particularly problematic. Even if +-*/ had been overloadable the expressions wouldn't have been much like what textbooks formulas looked like. No sigma for summation, no way to draw the square root symbol on screen, no Greek letters, division by / instead of horizontal line, a*b instead of ab, ...
When you get to matrixes the overloadable operators become an even smaller part of what Real Formulas look like.
Fortunately translating the Real Formulas to computer math wasn't particularly hard. Mathematicians have been doing it from the days of FORTRAN and even before.
The ability to overload kidergarten math operators would have made a small difference. Not big enough to bother, though, IMHO. Especially given the problems C++ has shown. Advantages vs disadvantages.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 25, 2005 11:46 PM
in response to: felipegaucho
|
|
|
>> doesn´t matter.. >> What we will gain with operator overloading ? >> what is the difference between to write: >> A + B; >> A.plus(B); >> just a few letters )
That is really so silly comment. I could not think that a programmer would write operator overloading just to make A + B
many applications are equation oriented. I mean that it so important for the programmer to see the exuation as it is written on the paper to be able to figure the correctness of his application.
all statements that say overloading make code ambijious are false.
because If I am going to overload a + or * operator that mean I am going to use it extensively and my application will have alot of equations.
and for my code reader, it would be important to see the equations to be able to know what are the equations. He will have to read the definition of + or * just once but then the equation of my application will be very nice to understand
I think those are againist operator overloading are oblivious of the context of their porgrams.
I just would overload operator only if really my application use equations extensively and for written A+B
All I see in this forum that all programmers are really inerested in having operator overloading but just sun programmers are againist.
why sun engineers negelects the needs of java progammers that much
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 26, 2005 7:12 AM
in response to: ramimahdi
|
|
|
> I mean that it so important for the programmer to see the exuation as > it is written on the paper to be able to figure the correctness of his > application.
What kind of mathematical software do you write where +-*/ makes your code look like mathematical texts? What field are you in?
Don't you need division ("/" is a poor substitute for a real horizontal line), multiplication (have to write "a*b" instead of mathematics "ab"), roots, dot product, matrixes, vectors, sets, factorial, union and other set operations, sum over, cartesian product, derivation, integration, partial integration, exponentiation, absolute value, postfix operators, subscripts, parenthesis other than (), percent, equivalence, negation, quantifiers (all/exists), disjunction/conjunction, membership, sub-/superset, ...?
Overloading +-*/ allows for kindergarten math at best. Although if I recall the first mathematical operators I was taught in school were union and intersection, so perhaps not even that.
> I think those are againist operator overloading are oblivious of the > context of their porgrams.
Some of us simply have too much experience with operator overloading and its rampant misuse.
> All I see in this forum that all programmers are really inerested in > having operator overloading but just sun programmers are againist.
Your assumption is incorrect. I suspect there are very few or no Sun employees in this thread. This is just too outlandish...
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 26, 2005 4:34 PM
in response to: sjasja
|
|
|
> Some of us simply have too much experience with > operator overloading and its rampant misuse.
Well then you should not be allowed to use it, hehe. But please give it to the rest of us, who know how to use it.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 26, 2005 8:49 PM
in response to: fuerte
|
|
|
yah I agree with you fuerte 100%
if for a software development company there is difficulty for their programmers to read operater overloading code, then the teams' leaders should put rules to their programmers not to use it.
But not to ask sun not to make it available for the others who get great benefits from operator overloading
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 27, 2005 4:18 AM
in response to: ramimahdi
|
|
|
One alternative to adding operator overloading to the language would be to use annotations on methods which we wished to see as operators together with a smart IDE/viewer that would display the code in operator form instead of the method calls that actually appeared in the file. Even better we would not need to restrict ourselves to the operators already in use, but could use any operator like symbol available in unicode. WHen typing code, the IDE could offer a list of relevant operations so we could mostly avoid the awkwardness of typing the more unusual operators.
Those who prefer operators can use an enhanced viewer, while those who prefer method form will look at the real file. Furthermore we have the assurance of several posters here that the method form will not be incomprehensible!
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 28, 2005 2:29 AM
in response to: fuerte
|
|
|
>> Some of us simply have too much experience with >> operator overloading and its rampant misuse. > > Well then you should not be allowed to use it, hehe. > But please give it to the rest of us, who know how to > use it.
Ok, I'll try to explain this once more.
Programmers don't live in a vacuum. They use other programmers' libraries and APIs. They need to maintain other peoples' code. A professional programmer needs to know his tools, including programming languages. The features and the interactions of features. A real programmer can't decide to ignore language features.
"You shouldn't be allowed to use it" -- the problem isn't me overloading "<<" to mean "output" (I wouldn't do that of course), it is that I need to use and maintain code written by others that is laden with such cute tricks.
In real world programming, "if you don't want to use feature X then ignore it" is not a valid argument for turning a language into a junkyard of features.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 28, 2005 10:01 AM
in response to: sjasja
|
|
|
> "You shouldn't be allowed to use it" -- the problem > isn't me overloading "<<" to mean "output" (I > wouldn't do that of course), it is that I need to use > and maintain code written by others that is laden > with such cute tricks.
I have a solution for your problem, believe or not. Make the operator overloading in Java so that it is always trivial (for the editor or compiler) to replace operators with function calls or vice versa. This way you could always have
new StringBuilder(new String({'a', 'b'})).Append(new String({'c', 'd'}).ToString()
instead of
"ab" + "cd"
even if the original writer used operator overloading.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 28, 2005 12:01 PM
in response to: fuerte
|
|
|
> I have a solution for your problem, believe or not.
That doesn't seem like a solution to overload abuse, it seems more like a new problem. I am at a loss as to how to make you understand the problem so you wouldn't try to find "solutions" to non-problems.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 28, 2005 7:34 PM
in response to: sjasja
|
|
|
can anybody here tell us how much is the cost of adding operator overloading to java in terms of developement cost of the SDK or if it has any conflict with existing features of java.
I think this cost is the real cause for sun engineers to be that much of hatred to operator overloading.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Nov 29, 2005 1:14 AM
in response to: ramimahdi
|
|
|
I don't think Sun engineers hate overloading any more (or less) than the Java community as a whole. The opposition to overloading is widespread amongst 'refugees' from C++.
|
|
|
|
|
|
|
|
Overloading impact
Posted:
Dec 2, 2005 7:26 AM
in response to: ramimahdi
|
|
|
> can anybody here tell us how much is the cost of > adding operator overloading to java in terms of > developement cost of the SDK or if it has any > conflict with existing features of java.
Hmm... Isn't it clear that the cost in terms of the impact to existing code is huge? a + b immediately becomes ambiguous and people would have to go hunting to figure out all of the types, any coercions (which auto-boxing would make even more nasty), etc.
|
|
|
|
|
|
|
|
Re: Overloading impact
Posted:
Dec 2, 2005 12:11 PM
in response to: johnm
|
|
|
> Hmm... Isn't it clear that the cost in terms of the > impact to existing code is huge?
It is none, because the existing code does not use operator overloading.
> a + b immediately > becomes ambiguous and people would have to go hunting > to figure out all of the types, any coercions (which > auto-boxing would make even more nasty), etc.
a + b is already ambiguous, you have to know the type of a and b before you know what happens.
|
|
|
|
|
|
|
|
Re: Overloading impact
Posted:
Dec 4, 2005 7:56 PM
in response to: fuerte
|
|
|
> > Hmm... Isn't it clear that the cost in terms of the > > impact to existing code is huge? > > It is none, because the existing code does not use > operator overloading.
Okay, you're scaring me. The instant that you add general operator overloading, all of the non-ambiguous, existing code will suddenly be open for interpretation. That's exactly the problem.
|
|
|
|
|
|
|
|
Re: Overloading impact
Posted:
Dec 4, 2005 8:55 PM
in response to: johnm
|
|
|
> Okay, you're scaring me. The instant that you add > general operator overloading, all of the > non-ambiguous, existing code will suddenly be open > for interpretation. That's exactly the problem.
I don't think it is being proposed that operator overloads can appear as free functions. Or that operators such as == or = be overloadable.
Given two references to BigInteger, a and b. There is no current meaning to the expression a + b. With an operator overload declared in the BigInteger class, it could be given a meaning. A meaning only definable by the BigInteger class. Subclasses needn't be allowed to override the overloading in general (although the operator override could forward to a virtual instance method).
It becomes more difficult where the types are different. But there are ways around it.
|
|
|
|
|
|
|
|
Re: Overloading impact
Posted:
Dec 5, 2005 9:22 AM
in response to: tackline
|
|
|
> > Okay, you're scaring me. The instant that you add > > general operator overloading, all of the > > non-ambiguous, existing code will suddenly be open > > for interpretation. That's exactly the problem. > > I don't think it is being proposed that operator > overloads can appear as free functions. Or that > operators such as == or = be overloadable.
(A) That's not how I read the many comments for op-ov in this thread.
(B) If you didn't, where are you going to draw the line? It's a very slippery slope because everybody and their cousin has that one area where they just "know" that it's worth all of the hassle, cost, risk, etc. That's the C++ disease.
> Given two references to BigInteger, a and b. There is > no current meaning to the expression a + b. With an > operator overload declared in the BigInteger class, > it could be given a meaning. A meaning only definable > by the BigInteger class. Subclasses needn't be > allowed to override the overloading in general > (although the operator override could forward to a > virtual instance method).
If you allow op-ov in Java than anybody looking at "a + b" has to go hunting around for exactly what a and b are to try and figure out what that means. Right now the usages of + for primitives and strings are distinct enough looking that that's only mildly annoying. Allow it for anything and it will always been confusing.
|
|
|
|
|
|
|
|
Re: Overloading impact
Posted:
Dec 5, 2005 9:31 AM
in response to: johnm
|
|
|
>If you allow op-ov in Java than anybody looking at "a + b" has to go hunting around for exactly what a and b are to try and figure out what that means.
this is silly argument
because if I read a.add(b) I should go to hunt around to find what this means
|
|
|
|
|
|
|
|
Re: Overloading impact
Posted:
Dec 5, 2005 11:36 AM
in response to: johnm
|
|
|
> > > Okay, you're scaring me. The instant that you > add > > > general operator overloading, all of the > > > non-ambiguous, existing code will suddenly be > open > > > for interpretation. That's exactly the problem. > > > > I don't think it is being proposed that operator > > overloads can appear as free functions. Or that > > operators such as == or = be overloadable. > > (A) That's not how I read the many comments for op-ov > in this thread. > > (B) If you didn't, where are you going to draw the > line? It's a very slippery slope because everybody > and their cousin has that one area where they just > "know" that it's worth all of the hassle, cost, risk, > etc. That's the C++ disease.
The C++ language disease was making std::string work. Java does not have the problems of memory management, different ways to reference memory, backward compatibility with C, etc.
> If you allow op-ov in Java than anybody looking at "a > + b" has to go hunting around for exactly what a and > b are to try and figure out what that means. Right > now the usages of + for primitives and strings are > distinct enough looking that that's only mildly > annoying. Allow it for anything and it will always > been confusing.
A big advantage Java has over C++ is that the common library is established and well used. Put together with the lack of "latent typing", the foundations are secure. If java.util.Set does not to define + to copy the left hand side and addAll to the right hand side, it is highly unlikely to start meaning that with anyone else's implementation. Hopefully java[x].* bods realise + for String concatenation was a mistake.
So if you want to know what + does, it's addition (except for String). To find the details you (or your IDE) do potentially have to look up two classes (if you don't know either of them well).
|
|
|
|
|
|
|
|
Re: Overloading impact
Posted:
Dec 5, 2005 5:31 PM
in response to: tackline
|
|
|
> > > I don't think it is being proposed that operator > > > overloads can appear as free functions. Or that > > > operators such as == or = be overloadable. > > > > (A) That's not how I read the many comments for op-ov > > in this thread. > > > > (B) If you didn't, where are you going to draw the > > line? It's a very slippery slope because everybody > > and their cousin has that one area where they just > > "know" that it's worth all of the hassle, cost, risk, > > etc. That's the C++ disease. > > The C++ language disease was making std::string work. > Java does not have the problems of memory management, > different ways to reference memory, backward > compatibility with C, etc.
What does all of that have to do with the topic of this thread? The "C++ disease" is that slippery slope style of *thinking*, not any one feature.
> > If you allow op-ov in Java than anybody looking at "a > > + b" has to go hunting around for exactly what a and > > b are to try and figure out what that means. Right > > now the usages of + for primitives and strings are > > distinct enough looking that that's only mildly > > annoying. Allow it for anything and it will always > > been confusing. > > A big advantage Java has over C++ is that the common > library is established and well used. Put together > with the lack of "latent typing", the foundations are > secure. If java.util.Set does not to define + to copy > the left hand side and addAll to the right hand side, > it is highly unlikely to start meaning that with > anyone else's implementation. Hopefully java[x].* > bods realise + for String concatenation was a > mistake. > > So if you want to know what + does, it's addition > (except for String). To find the details you (or your > IDE) do potentially have to look up two classes (if > you don't know either of them well).
Huh? The topic is what happens if we add op-ov to Java. The proponents of op-ov think that op-ov won't have any negative effects on existing code and coders and the fact is that it will.
|
|
|
|
|
|
|
|
Re: Overloading impact
Posted:
Dec 5, 2005 8:00 PM
in response to: johnm
|
|
|
> What does all of that have to do with the topic of > this thread? The "C++ disease" is that slippery > slope style of *thinking*, not any one feature.
The pathogen of C++ thinking is C++. Assuming Java programmers are programming in Java, C++ think is not a problem. If programmers tried to apply operators inappropriately, then it would stick out like a sore thumb.
I admit when I was learning C++ I used >> and << to read and write bytes to and from a pixie. However, I was following the library design, I didn't actually use the "STL" part of the standard library at all and it was just a beginners mistake. If Java gained operator overloading then to repeat the mistake newbies would have to somehow entirely ignore the library and never learn. Far worse crimes happen in Java.
> Huh? The topic is what happens if we add op-ov to > Java. The proponents of op-ov think that op-ov won't > have any negative effects on existing code and coders > and the fact is that it will.
Do you mean it will have effect on the semantics of any existing code (certainly not true for any sensible implementation). Or do you mean, programmers will have to think whether + is being applied to int or BigInteger, even in old code (that's a problem??).
|
|
|
|
|
|
|
|
Re: Overloading impact
Posted:
Dec 6, 2005 9:41 AM
in response to: tackline
|
|
|
My 2 cents... let Sun define a minimalist set of operators for well-understood cases like String but do not allow developers to define their own. Generics, in its current form, deserves the same attitude in my view. It is all too attractive to try it for your code and the benefits do not outweigh the high probability you will run into problems with it (due to lack of flexibility).
Start with well-understood cases first. If that works well and it makes sense to generalize the approach, open up the system to everyone else.
Gili
|
|
|
|
|
|
|
|
Re: Overloading impact
Posted:
Dec 6, 2005 12:57 PM
in response to: cowwoc
|
|
|
> My 2 cents... let Sun define a minimalist set of > operators for well-understood cases like String but > do not allow developers to define their own. > Generics, in its current form, deserves the same > attitude in my view. It is all too attractive to try > it for your code and the benefits do not outweigh the > high probability you will run into problems with it > (due to lack of flexibility).
What. Generics must be used by every programmer if he ever uses Hashtable, for example. You can't use it without generics, or at least you should not to.
> Start with well-understood cases first. If that works > well and it makes sense to generalize the approach, > open up the system to everyone else.
Because operator overloading would not affect existing code, and it should only be used with arithmetics and such, it probably would not be used by most programmers most of the time.
|
|
|
|
|
|
|
|
Re: Overloading impact
Posted:
Dec 6, 2005 1:09 PM
in response to: fuerte
|
|
|
My point was that Collections should make use of Generics and developers could make use of Collections, but developers would not be able to create their own classes which make use of Generics.
Same thing would go with operator overloading. Sun would define the use of Generics and operator overloading over a small and well-understood subset of Java and developers would not be able to add their own.
Gili
|
|
|
|
|
|
|
|
Re: Overloading impact
Posted:
Dec 6, 2005 4:16 PM
in response to: cowwoc
|
|
|
> My point was that Collections should make use of > Generics and developers could make use of > Collections, but developers would not be able to > create their own classes which make use of Generics.
Okay, sorry that I didn't get it at first. That makes a lot of sense (in most cases).
> Same thing would go with operator overloading. Sun > would define the use of Generics and operator > overloading over a small and well-understood subset > of Java and developers would not be able to add their > own.
That again makes sense in most of the cases, but not always. Some people would like to add them, so it should not be forbidden. In practise the feature would not be used (in that sense) by most of the programmers.
|
|
|
|
|
|
|
|
Re: Overloading impact
Posted:
Dec 6, 2005 1:28 PM
in response to: fuerte
|
|
|
> Because operator overloading would not affect > existing code, and it should only be used with > arithmetics and such, it probably would not be used > by most programmers most of the time.
IMO, operator overloading should be used by most programmers "most of the time". ints and longs have nasty, silent overflow behaviour. Therefore BigInteger, or something slightly more efficient, is probably a better idea for non-low level code. The same goes double for decimal and rational types.
|
|
|
|
|
|
|
|
my latest thoughts on overloading, etc.
Posted:
Dec 31, 2006 1:45 PM
in response to: cowwoc
|
|
|
> My 2 cents... let Sun define a minimalist set of > operators for well-understood cases like String but > do not allow developers to define their own. > Generics, in its current form, deserves the same > attitude in my view. It is all too attractive to try > it for your code and the benefits do not outweigh the > high probability you will run into problems with it > (due to lack of flexibility). > > Start with well-understood cases first. If that works > well and it makes sense to generalize the approach, > open up the system to everyone else. > > Gili
It seems that this thread will never die! Going back to my original proposal:
> Add operator overloading to Java but make it only usable > within the java.* and javax.* package hierarchies. This > would allow complex, interval arithmetic, matrix and > vectors, etc. to be added. It would allow JCP JSRs to > add well thought out operators while not allowing the > abuse that making the facility available to everyone > would lead to.
This is exactly what I suggested. Confining new operator overloads to the java.* and javax.* package hierarchies means that only well thought out operators that obey traditional mathematical usage will be included.
As it is at present Java is virtually useless for much scientific and engineering computing, as complex, interval, big decimal, matrix, etc. arithmatic is hard to write and read. Earlier this year I translated some reasonably complex highly mathematical algorithms from C++ to Java. The original algorithms were easy to understand using tradition math notation, the C++ algorithm was not too far from that, but the Java was almost impossible to read without having the original algorithm next to it.
My other proposal was for adding a "function" modifier that indicated the method had no side effects. I now think two modifiers would be needed "pure" indicating a pure function with provably no side effects, and "function" indicating a method with no visible side effects (but allowing caching, lazy evaluation and IO - at least output).
Both proposals would be greatly helped by value classes and an immutable modifier to classes to indicated that they cannot be changed after construction. Value classes again might be confined to the java.* and javax.* class hierarchies as they are really only useful to define small objects like complex which should have pass-by-value semantics and be stored in arrays as values (not references). Immutable classes are much more general, knowing that an object cannot change after construction helps reasoning about a program and allows optimisation of many algorithms.
All four proposals (overloading, function, value objects, immutable) are really one package, they fit well together and are probably not worth doing individually.
The biggest problem with this is that all the existing Java libraries do not have any of them. Retrofitting existing libraries would be difficult, perhaps impossible.
I have come to the conclusion the best way forward would be to create a new Java like language with these features, generics done properly, the abolition of primitives, the abolition of casting, traits, closures, etc. This is a major challenge, I have made two attempts to create such a language, but in neither case did I consider the resultant language to be good enough for public viewing.
The Fortress language http://research.sun.com/projects/plrg/ comes close to what I'm looking for. It is I think a bit complex for the average programmer and the syntax is quite different than Java, but perhaps a Java like wrapper in the existing syntax (as a syntax expander) may work.
|
|
|
|
|
|
|
|
Re: my latest thoughts on overloading, etc.
Posted:
Jan 1, 2007 6:20 PM
in response to: m_r_atkinson
|
|
|
I have written an extended compiler:
http://pec.dev.java.net/nonav/compile/index.html
Using this compiler you can have immutable classes by implementing interface Immutable. The methods inside these classes are pure because these classes may only contain immutable fields.
If you do try the compiler out let me know how you go.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Dec 1, 2005 12:14 AM
in response to: fuerte
|
|
|
> I have a solution for your problem, believe or not. > Make the operator overloading in Java so that it is > always trivial (for the editor or compiler) to > replace operators with function calls or vice versa. > This way you could always have >
The solution is to collect everyone who wants to add operator overloading and dump them in the Pacific ocean a thousand miles from the nearest land.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Dec 7, 2005 1:12 AM
in response to: m_r_atkinson
|
|
|
Why don't we make a poll proposal?
Do you think "operator overloading" would be a welcome feature in Java language?
a) NO!! I want to read my coworkers code and know what it does b) YES!! Give us the freedom to use operation overload in our classes c) YES.. but only on Number subclasses for the natural operation (+ - * /) d) YES.. but only on java.* javax.* classes and their addition should be approved by Sun
(Did I forget anything?)
Personally, I think that (a) will win.. I'm more on the (c)/(d) league but I'm curios to see if in the YES league we're more on (b),(c) or (d)
Last time I talked with a friend of mine about Operator Overloading, he said (and he was serious): Yes.. Why can't I write String s='a'*10; to say "aaaaaaaaaa"
That scared me
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Dec 7, 2005 1:48 AM
in response to: insac
|
|
|
The fact that the actual value of the expression 'a'*10 is 970 rather unfortunate. Justified I guess by the C/C++ inheritance. I tend to feel that treating char as 'unsigned short' with the full complement of math operators was not a good idea.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Dec 7, 2005 3:45 AM
in response to: mthornton
|
|
|
> The fact that the actual value of the expression > 'a'*10 is 970 rather unfortunate. Justified I guess > by the C/C++ inheritance. I tend to feel that > treating char as 'unsigned short' with the full > complement of math operators was not a good idea.
Hehe, good point. So overloading * here would be good in fact. Maybe it could be overloaded to result in compiler error???
And think about "a" + 10, it is a valid Java expression, using built-in operator overloading, resulting in "a10".
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Dec 8, 2005 2:04 AM
in response to: fuerte
|
|
|
> > And think about "a" + 10, it is a valid Java > expression, using built-in operator overloading, > resulting in "a10".
That's not operator overloading, it's an unfortunate case of 2 operators using the same symbol.
Operator overloading would have you type something like: [code] class Orange {} class Apple {} class Banana {} ... Orange orange = new Orange(); Apple apple = new Apple(); Banana banana = apple^orange + orange - apple;
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Dec 8, 2005 4:27 AM
in response to: insac
|
|
|
> Why don't we make a poll proposal? > > Do you think "operator overloading" would be a > welcome feature in Java language? > > a) NO!! I want to read my coworkers code and know > what it does > b) YES!! Give us the freedom to use operation > overload in our classes > c) YES.. but only on Number subclasses for the > natural operation (+ - * /) > d) YES.. but only on java.* javax.* classes and > their > addition should be approved by Sun
I'm game, though I might have to shorten the descriptions a little bit.
Any other thoughts on this? New polls go up on Fridays.
--Chris (invalidname) Editor, java.net
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Dec 9, 2005 2:04 AM
in response to: chrisadamson
|
|
|
> > Why don't we make a poll proposal? > > > > Do you think "operator overloading" would be a > > welcome feature in Java language? > > > > a) NO!! I want to read my coworkers code and know > > what it does > > b) YES!! Give us the freedom to use operation > > overload in our classes > > c) YES.. but only on Number subclasses for the > > natural operation (+ - * /) > > d) YES.. but only on java.* javax.* classes and > > their > > addition should be approved by Sun > > I'm game, though I might have to shorten the > descriptions a little bit. > > Any other thoughts on this? New polls go up on > Fridays. > What about simply: Do you think operator overloading is a good idea? 1) No 2) yes
And another one: Should Sun add everything anyone ever suggested to the core language? 1) hell no 2) sure, why not
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Dec 9, 2005 6:44 AM
in response to: jwenting
|
|
|
> What about simply: > Do you think operator overloading is a good idea? > 1) No > 2) yes
 That's too easy..
It's a good idea that can be horrendously misused..
Unless somebody finds a way to avoid its misuse, "operator overloading" wouldn't be a welcome addition. That's why I tried adding two of the proposals that has emerged from this forum to try avoiding its misuse by developers.
> And another one: > Should Sun add everything anyone ever suggested to > the core language? > 1) hell no > 2) sure, why not
1) hell no (but there's nothing wrong in discussing ideas and try to find pros, cons, opportunities and constraints of new features)
However, don't worry.. it seems the majority of Java developers agree with you that the "operator overloading" is not a welcome feature.
Bye, Fabio
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Dec 9, 2005 12:17 PM
in response to: insac
|
|
|
> However, don't worry.. it seems the majority of Java > developers agree with you that the "operator > overloading" is not a welcome feature.
"Don't worry"? That's exactly the reason to be worried!
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Jan 11, 2006 9:20 AM
in response to: fuerte
|
|
|
why it is always said that the majority of java developers are not welcomming operator overloading
this is a big tail.
why don't u make some survey or voting and I am sure that supporters of operator overloading will exceed 70%
so stop this big false saying please
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Jan 11, 2006 11:50 AM
in response to: ramimahdi
|
|
|
> why don't u make some survey or voting and I am sure > that supporters of operator overloading will exceed > 70%
http://today.java.net/pub/pq/83
57% opposed operator overloading. Of course polls of this sort should always be taken with a large dose of salt, but you aren't going to get a more reliable result without spending quite a bit of money.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
Posted:
Jan 24, 2006 2:12 PM
in response to: mthornton
|
|
|
Answer such as "it's complicate", "people will abuse it" should be discarded. If and only if the answer is in favor of operator overloading, I would poll people about how.
To me, if the language could enforce or strongly encourage preservation of the operator attributes (commutativity, associativity and so on), I would be very glad to have operator overloading. For instance, to specify that there is no guarantee that a + ( b + c ) will not become c + ( b + a ) at run-time. If it can be done efficiently, as post 71 proposes, that's even better.
|
|
|
|
|
|
|
|
Re: Operator overloading (again) and functions
| | | |