|
Comments
|
Submitted On 26-APR-1999
Ray Burns
>it may be possible to recognize this and allocate it on the stack.
Think about it some more. It is NOT possible. NO implementation improvement
can fix this issue, which leaves us at your mercy.
The main issue is much more than performance. Compare:
(a,b) = o.func();
vs
Pair p = o.func();
a = (SomeType)p.v1;
b = ((Integer)p.v2).intValue();
The main issues are:
1. Type safety
2. Code readability
3. Performance
Please reconsider.
Submitted On 03-MAY-1999
mkienenb
I dealt with this using
public Object[] method()
{
Object result[] = Object[2];
...
return result;
}
For Objects, you lose typecasting, which is
painful, but for more primitive types, it
should work fine and be much more efficient.
Submitted On 11-APR-2000
dkf
If you had a generic Pair class (see the generics proposals
floating around) then you could pass back two object values
without massive code bloat, and with compile-time type
safety.
Submitted On 10-NOV-2000
nissenbenyitskhak
The arguments against this proposal rely on the idea that it is somehow
better to create Object tuples to encapsulate the multiple return values,
which eschews type safety, or to create new typesafe classes.
The latter is certainly a workaround, and there may be cases where it is
even preferred, but let's consider another example.
String someText = "The quick brown fox jumped over the lazy dog's back";
String token = "";
for (;;) {
(token,someText) = removeToken(someText);
// removes next token from someText
if (token.length() == 0) break;
doSomething(token);
}
This is the parsing equivalent of iteration!
If we could change class String and add a removeToken method to it,
we wouldn't need the multiple return values because we could just
say:
token = someText.removeToken();
which would modify someText as a side effect.
Without multiple return values, one must create a class that
represents a scanned state of someText, which is somewhat
analogous to using an Iterator to look at the elements of
a collection. Then one must posit the valid sequence of
operations on this new class (e.g., you must initialize it
before calling removeToken(), etc., you must enquire
about its state somehow). There is computational
and memory overhead, and conceptual overhead for
the programmer.
Many languages provide call by reference. This enhancement
provides the same functionality, except that it becomes clear
syntactically which parameters are being changed.
Submitted On 04-AUG-2001
acoliver
I REAAAALLY hope they close this as will not be fixed. Its
VERY simple to fix it:
public int[] myResult() {
int[] result = new int[2];
result[0]=1;
result[1]=2;
return result;
}
There's your two numbers. Now should you need something
goofy like mixed values then Object arrays. as for mixed
primitives, the real bug is java should fascade all
primitives as if they were objects without them being such.
Submitted On 27-AUG-2001
jdcjdc
Almost every language has a way to return multiple values:
C/C++: pointers, Pascal: var, BASIC: (by default).
Java is an exception. All method parameters in Java are passed 'by-value' and only
one value can be returned. This means, you have write ugly non-intuitive
code to return multiple values.
Simple example: swap two integers
class Myutil {
// without multiple return values -- ugly hack
public static int[] swap_old(int a, int b) {
int[] ret = new int[2];
ret[0] = b;
ret[1] = a;
return ret;
}
// with multiple return values -- pretty cool
public static (int, int) swap(int a, int b) {
return (b, a);
}
}
Which is better?
Submitted On 09-FEB-2002
lotusalife
Re:"``it may be possible to recognize this and allocate it
on the stack.'' - Think about it some more. It is NOT
possible. [...]"
Few things are *impossible* - and this is not one of them.
Submitted On 18-FEB-2002
pranal
i guess this is the way
public int[] myResult() {
int[] result = new int[2];
result[0]=1;
result[1]=2;
return result;
}
we have two numbers.
if there is a need for dicy mixed values then Object arrays.
Submitted On 20-FEB-2002
jjppreilly
This is the syntax used in Python and Jython. It is a
great saving in terms of code and more important code
readabity. Using arrays and generic classes are possible
but add code and detract from readability.
PS: We use jython a lot for testing out java classes - it
is excellent.
Submitted On 15-APR-2002
spf1
It seems this bug is getting fixed for 1.5. See (and
possibly shift your votes to) Bug 4639379.
Submitted On 10-SEP-2002
codymanix
where is the problem here??? the solution is sooo simple and
can be solved with the standard java without any extra
extensions:
int[] divide(int a, int b)
{
return new int[]{a/b, a%b};
}
or maybe this way:
void divide(int a, int b, Result res)
{
res.q=a/b;
res.r=a%b;
}
most programming language DO NOT support multiple return
types and there are reasons for it.
Submitted On 20-OCT-2002
jdcjdc
cody,
Your workaround has several drawbacks:
* Tedious - a new Result class needs to created each time
a method desires to return multiple values
* Slow - Result requires new() to create it on the heap and
additional overhead by the garbage collector to free it.
Ideally, the return values should be allocated on the stack
which would an order or two faster than your solution
* Less readable - the proposed solution is obviously more
readable that your solution
* Unsuitable for functioonal languages - Java's VM is also
used for implementing several functional languages. If
you've looked at functional code, you'll see lot of multiple
return values there. Adding this feature will it easy to
create functional language compilers targeting the JVM
I'm sure there are hacks to work around flaws in the
language. But that does not mean these should be put into
widespread use.
Submitted On 17-JAN-2003
shrink_laureate
> most programming language DO NOT support multiple
> return types and there are reasons for it.
Really? What reasons? I've yet to see a single reason,
except that it would take some effort to implement (hardly a
good one). What do you have against multiple return types?
Most languages have convenient workarounds for the lack of
multiple return types. Java has inconvenient workarounds.
I'd far prefer the feature itself.
Submitted On 29-JAN-2003
MartDesruisseaux
MatLab support multiple return values, as many languages in
the scientific community.
Submitted On 21-MAY-2003
poke1024
Eiffel's solution is quite elegant, if I remember right
order (a, b: INTEGER): TUPLE [a, b: INTEGER] is
do
if a <= b then
Result := [a, b]
else
Result := [b, a]
end
end
Submitted On 21-MAY-2003
kaisersoze
A return value is merely a special case of an "out" param.
Java must simply support out params and everyone will be
happy. Note that they are type-safe, do not involve raw
pointers, and assignment is compile-time checked.
Here is a C# sample:
void Decode(string address, out string name, out string
domain)
{
string[] s = address.Split('@');
name = s[0];
domain = s[1];
}
Here is a sample of a call to such a method. Note that the
"out" keyword is also used here, for clarity.
void Test()
{
string name, domain;
Decode("123@somewhere.com", out name, out domain);
}
Submitted On 21-MAY-2003
jimthev2
It is a travesty that multiple return values are not
supported. The workarounds listed in the bug and in the
comments explicitly show the need for a better way. The
hardest parts of our codebase to understand (eg. which
parameters are being passed as input values and which are
being passed as placeholders for return values) and hence
the greatest error producing parts could be cleared up with
multiple return values. Jeeze, just let me put more than
one item on the return stack. I can live w/o multiple
inheritance, but the idea that either a method only has a
single result or has to lead to code bloat is acceptable
only to people that don't write complex code. The quote
that the examples are 'spurious' shows lack experience
and/or imagination. Creating, filling and then assigning
values out of these recommended arrays is exactly the
definition of inefficiency and code bloat. This bloat costs
me and my staff time and money.
Submitted On 22-MAY-2003
pazu
No, no... multiple return values are not a special case of
"out" parameters; that's the other way around: "out"
parameters are an ugly hack to emulate multiple return values.
Think clearly: parameters are what a method needs to
operate. They are *input* values that customize how a method
works. out parameters are nonsense.
While I agree that returning arrays or custom types are a
solution for multiple return values, it would be very nice
if the language itself supported it. Take a look at Python,
folks. It's still time to include this feature for Tiger.
Submitted On 22-MAY-2003
loftling
public class CrazyResult
{
public int value;
public String name;
}
...then:
public CrazyResult getCrazy (List param1, Map param2,
CrazyResult result)
{
if (result == null) {
result = new CrazyResult();
}
// calculation omitted
result.value = somevalue;
result.name = somename;
return result;
}
The caller can decide whether to avoid object creation by
keeping one CrazyResult instance around. This solution is
type safe, easy, understandable, and already used in many of
the standard java libraries.
Submitted On 25-MAY-2003
chaotica
i have to wonder....isn't it kinda against the principles of OOP
to have functions returning a bunch of heterogeneous,
unwrapped, but related data? shouldn't such data be in a
class anyway?
Submitted On 26-MAY-2003
brucechapman
Chaotica,
The answer is YES. I was going to right something but you've
said it all.
Submitted On 28-MAY-2003
kennethxu
With almost similar working experiece and knowledge of
various languages. I strongly agree with the bug reporter that
java should allow multiple return value.
Regarding to the argument of againsting OO principles. If this
stands, isn't that java shouldn't allow multiple paramaters?
Submitted On 11-JUN-2003
shrink_laureate
In many cases, yes, this is against OO principles: if the
things you want to return form a single 'thing' then they
should be made into an object.
But this is not always the case. Sometimes, return values
really are independent. Both tools should be available.
Submitted On 09-SEP-2003
xtarka0
I am not voting on this request. I am merely stating my
observations about it.
It seems like you are asking the compiler to define and
instantiate a hidden "helper class" that wraps the multiple
return types into a single container. The "return (x,y,z);"
would be converted to instantiate a new object of the helper
class, the fields assigned the values, then the object is
returned. The calling method receives the object and the
compiler generates the code to unwrap the helper object.
This is what programmers must do now by hand. The compiler
can probably do it better, including dealing with the issue of
making the wrapper class accessible to other compilation
units (so that other compilation units know what return type
to expect). Pushing multiple return items onto the stack is
probably not a good idea, because it would impact the
current implementation of garbage collection (thus implying a
JVM change). (A JVM change is a very serious matter. A
compiler change is much easier to negotiate and implement.)
The compiler is already allowed to generate "helper" classes
and methods, according to the Java Language Spec and the
JVM spec (they are called "synthetic" classes and methods).
Using synthetically generated wrapper classes and compiler-
generated wrapping and unwrapping code would not involve
any JVM change. Such classes would be to be similar to
anonymous inner classes, but they would be static (not have
an implicit reference to an outer class).
There would be an issue with separate compilation of code
calling the multiple-return method versus the compilation of
the multiple-return method. Somehow, the compiler must
ensure that the synthetic wrapper class expected by the
calling method is the same wrapper class used by the called
method. This can be done by inserting a cast of the return
value to ensure that the same wrapper class is used in both
code locations.
In summary, this request for multiple-return values appears to
be a compiler change and not a JVM change. Efficient
garbage collection can reclaim the wrapper object quickly
after its values are unwrapped. No other thread can see the
wrapper object, so synchronization is not an issue.
2 cents worth. Your mileage may vary.
Submitted On 03-NOV-2003
christopher_j_nielsen
IMHO, extending the Java language to support multiple return
values, defeats one of the original goals of Java: simplicity.
For those who have never read James Gosling's original Java
white paper, check out:
http://java.sun.com/people/jag/OriginalJavaWhitepaper.pdf
The example cited by the bug -- that of two integer return
values -- seems a bit contrived to me. How are these two
integers related to one another? Presumably they are related
in some manner, otherwise you would not be returning them
together? And would it not make sense to encapsulate these
two values in an object? (The latter -- the concept of
encapsulation -- is a mighty basic aspect of object-oriented
development.)
Regardless, let me cite two real-world examples from the
AWT. Both of these objects encapsulate tightly-coupled
values:
java.awt.Dimension: represents the width and height of a
graphical object.
java.awt.Rectangle: represents the bounds of a graphical
object.
To allow developers to avoid unnecessary allocations, the
developers of AWT provided two variants of methods
getBounds() and getSize(), in java.awt.Component:
// these allocate new objects on the heap
Rectangle getBounds()
Dimension getSize()
// these utilize the passed-in objects, filling in values and
returning them
Rectangle getBounds( Rectangle rv )
Dimension getSize( Dimension rv )
The two latter methods allow the caller to provide the
allocated object, and provide exactly the efficiency the
author of this bug desires.
IMHO, anyone who argues that "it is too much work" or "too
inefficient" to define objects for "something so simple as two
integer values," does not understand the power/elegance/etc.
of OOP development. I respect the opinions of you anti-OOP
folks -- just don't ask Sun to inject features to support anti-
OOP development, in a nearly-pure-OOP language like Java.
[Suggestion to Sun: close this RFE, and mark as 'defeats goal
of Java's simplicity'.]
Submitted On 16-NOV-2003
abies
christopher, in 1996 I would read your comment and applaud.
But java is not as simple language as back then. Anonymous
classes, variance-based generics, annotations/meta-data,
rich enums, ... arg notation - all these things which will be in
1.5 (except anonymous classes, which already are in,
together with silent generation of accessors, magical
enclosing class access syntax etc).
Simplicity is not longer an argument 'just because'. You need
to balance simplicity and expresiveness(sp?) - and, as 1.5
clearly shows, sometimes simplicity loses the battle.
Submitted On 08-DEC-2003
masanao
xtarka0,
I have an question.
> ( x , y ) = getValues( a, b );
If this notaion is implemented , this could be an atomic
(assign) operation?
I believe it must be an atomic assignment operation,
(because it is seen so)
but It seems it requires JVM change not only Compiler change.
Quick fix is a danger ,isn't it?
Anyway, I like this notation to express a couple of value
simply.
Though JVM is required to change, I'm eager for it.
Submitted On 10-DEC-2003
masanao
jarouch,
I know 'long' and 'double' assignment operation is not
atomic operations on specification.
But almost all JVMs implements them as atomic operations,
because it is clear to understand for programmers.
I think this is as same as 'long' and 'double' case.
Submitted On 10-DEC-2003
jarouch
Why atomic? F.e. assigning of long and double is not
atomic operation too.
Submitted On 01-JAN-2004
jdcjdc
Does anybody know how this will be implemented in Tiger? If
it's just a hack returning Object[], I'll be sorely
disappointed. Ideally, the language and VM should change to
return multiple values on the stack, instead of heap (new
Object[]).
Submitted On 14-JAN-2004
jarouch
Masanao,
I still don't see reason for it. Truth is, atomicity looks
like nice feature, but i think it is connected with much
more implementation problems and overhead then
simple solution. And better simple than nothing;). And
you can always synchronize changes..
Btw. supposing that 'almost all JVMs implements
something' is nice way to hell..
jdcjdc
Where did you see this feature should be implemented
in Tiger?
Submitted On 15-JAN-2004
jdcjdc
jarouch,
Bug 4639379, is where I got the impression that this feature
will be in Tiger.
As far as atomicity is concerned, few people care for it in
this case. And no, almost no VM supports atomicity of longs
and doubles on 32-bit processors. To support atomicity on
these CPUs would harm performance too much.
By the way, anyone have good ideas on the syntax?
a)
(String name, int salary) getEmployeeInfo( int empId)
{ return (name="Jon Doe", salary=50000); }
OR
b)
(String, int) getEmployeeInfo( int empId )
{ return ("Jon Doe", 50000); }
I think (a) is more descriptive, though slightly unorthodox.
Submitted On 27-JAN-2004
FatihC
Much as I would like to see this feature to be
implemented in Java 1.5, I fear it wont be done that
soon.
All these nice code examples you show, still they are
all workarounds themselfs!
Best would be to introduce a new type "Tuple".
Think about the following examples:
(int, int) makePair(int a, int b)
{
return (a,b);
}
int add(int a, int b)
{
return a+b;
}
Should it be allowed to use this methods like the
following:
(int, int) pair = (5,2);
(int, int) anotherPair = makePair(8,9);
int result = add(makePair(3,8));
int anotherResult = add(pair);
...
I think you have not ment this kind of feature, although
it is not far away from what you are suggesting.
It would be illogical to implement only the possibility to
return multiple values, without this new Tuple types.
I'd like to see this tuple type in Java, but it is to much to
do and to big changes. They wont come in Java 1.5.
And I do not think they are going to do "half work" and
only implement it the way you suggest.
Submitted On 28-JAN-2004
jarouch
Why just workarounds? If I need to return more than
one value cause creation of wrapper is slow and eats
memory, i need not another kind of compoud type to do
it. In such case workaround is using wrapper classes,
arrays or tuples to achieve this..
Tuples can give you a posibilities which multiple return
values can not, variables of tuple type and so, but it is
again some compoud type and so it will lead to
memory and cpu overhead..
What should be good - combination of this two
aproaches. It can have same syntax, cause compiler
always knows if you are asigning to tuple or to group of
variables, so can generate optimal code.
Submitted On 04-FEB-2004
jdcjdc
FatihC,
IMO this RFE is about two things:
a) a solution to returning more than one value from a method
without creating a new Results class or using type-unsafe
Object[].
b) solving (a) in the most efficient (speed, size) way
possible.
Although (b) would be good to have, I can live with a
solution if we get (a) but not (b).
Your tuple proposal is simply a redundant way to declare
unnamed classes on the fly:
(int, int) pair = (1, 2);
Here, pair is an object belonging to an unnamed class that
contains two ints. Java's class system is a better way to
create classes and therefore your addition is both redundant
and confusing. This solution is also slow, requiring heap
object allocation for the 'pair' object.
The solution to this RFE should be targeted towards methods
that return multiple values, but where it does not make
sense to create a new dummy class to hold multiple values.
If it turns out that the returned values need to be combined
into a single object, like the 'Tuple' object you mention,
then it would be better instead to create a new custom class
like 'FooResults' to hold those values. In other words,
Tuple seems redundant to me.
Submitted On 14-APR-2004
zorzella
This is really useful, even more so when talking about
remote methods, such as an EJB call. Say I want to get
"windowed" results (e.g. a page of results in a DB query),
but I'm interested in knowing how many entries are there in
total.
******************
MyStuff[] stuff;
int from = 0;
int to = 10;
(stuff, size) = mySessionBean.getStuffFrom (from, to);
******************
The only 2 ways are to create wrapper classes, either one
for each type of return array (bad bloat of useless
classes), or one that needs typecasting aftetr return (bad
coding principle, loosing compile-time type check).
Submitted On 29-JUL-2004
MadPr0grammer
why not just do something like C++'s reference parameters?
void f(int &x, MyClass &c) {
x = 5;
c = new MyClass();
}
that way, you could keep your type saftety, it would work on both Objects and primitives, and also be really familiar to us coming from C++.
Submitted On 13-SEP-2004
gweedo
RFE's need a vote AGAINST option, rather than just a vote for. Consider this a vote against this enhancement. Talk about mucking up a language unnecessarily... pretty soon Java will be just as ugly as C++ if this goes through.
Submitted On 14-SEP-2004
nekola
gweedo:
Yes, I prefer easy to understand languages with minimalistic syntaxe. But Java decided to be a succescor of C family of languages. And thats why it can not be minimalistic (it already is not minimalistic) and must prefer pragmatic decisions.
The multiple return values can be usefull in lots of situations and thats why I found it pragmatic. It's much more systematic solution to use a build in construct with no overhead than to develop own ad-hoc solutions (non reusable wrappers...). I also think, that returning multiple values is a natural extension of the concept of returning value and so it's easy to understand.
<br />
C++ doesn't have such as feature, because it has slightly different philosophy with construct such as pointers and references. But pointers are hell and multiple return values don't bring such as problems.
Submitted On 20-SEP-2004
intangir2
This is a performance and a language issue.
Performance issue could be solved by stack allocation.
It is possible (just look at C++: it allows stack and
heap allocation for same class). JVM only needs to do
some dataflow analysis to find out wheter some object
can or cannot be allocated on stack.
I think the language issue would be worked on only
after performance issue is solved. That's why I
suggest for you folks to vote on
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4809540
and after it's solved, go back and vote on this bug.
Submitted On 30-SEP-2004
aldo_g
The actual solution for (Please allow Multiple Return Values) could be:
( -) returning a Map (I think is the better because you can name each returned parameter);
if you use this for encapsulating an Oracle store procedure is the best
way because de Oracle Database boys change very often the number of
out parameter of his store procedures, and because you can return a
messageError also, or anithing you whant.
The cons are you are not using java type safety characteristics, but
(-) returning an Array
The pros if all returning parameters are the same type you can
use an array of that class (Use only in this case, if the type is Object
is better to use a Map).
The cons(you must now in which index is the variable you want)
(-) returning a Class:
pros: you are always sure that the returned parameter is in the correct
type, its useful when you whant to return for example a point(X,y),
cons: create a class for each function that must return many output
parameters is ugly (to many clases more and files) especially if the
parameters are unrelated
(-) passing an Array or Map like input parameter and filling this before
returning, i think this is ugly.
If you only whant to return a value and a erro message you can use an Exception
int foo(.....) throws SomeException;
The posible solutions:
(-) Create a class like a Tuple that can be used like a Map
but in which you can tell which type is each parameter
(may be using java 5 anotations) and then the compiler
could check type safety, maybe this could be implemented
in the compiler for type safety, but not in the JVM
The JVM will see a normal Map return type.
(-) Creating a parameter by Reference, i know then you
can't return 8 parameters when you receive only 6 parameters
but anyway java must support this to allow the integration
of many languages like .NET
I think this is not a trivial or foolish request of enhancement
some programs of higher level of abstraction, like funtional programs
can return functions or many parameters, the result is an very legible
code, I think we have to think clever forms to achieve this in the
future for the Java plataform
Submitted On 13-OCT-2004
galabar001
It sure would be nice to be able to do this:
(int,int) foo() {
return (1,2);
}
(int i, int j) = foo();
:-)
Submitted On 13-OCT-2004
galabar001
It sure would be nice to be able to do this:
(int,int) foo() {
return (1,2);
}
(int i, int j) = foo();
:-)
Submitted On 25-OCT-2004
hlovatt
In J5 you can use this:
public class Tuples {
private Tuples() {}
public static class T2< E1, E2 > {
public final E1 e1;
public final E2 e2;
public T2( final E1 e1, final E2 e2 ) {
this.e1 = e1;
this.e2 = e2;
}
}
public static < E1, E2 > T2< E1, E2 > t2( final E1 e1, final E2 e2 ) {
return new T2< E1, E2 >( e1, e2 );
}
// T3 etc.
}
Then to define a method and use the method that returned the tuple you would write:
import static Tuples.*;
....
T2< Integer, Integer > foo( int x, int y ) {
return t2( x, y )
}
....
T2< Integer, Integer > r = foo( 1, 2 );
Maybe this RFE should simple ask for a tuple class to be
added to the standard library :)
Submitted On 26-OCT-2004
jarouch
But you still have to create new instance of this tuple. Declaration of tuple variable with more elements will be long (imagine your example extended to T9;), and you can not use primitives. I know, we have autoboxing, but it just leads to more object creations..
Submitted On 26-OCT-2004
hlovatt
jarouch,
You raise a number of points:
1. But you still have to create new instance of this tuple.
Yes, but they are quick to create on a modern JVM. If you
want quicker object creation and deletion then vote for:
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4617197
This is a much more general solution to stack allocation
than just multiple return types.
2. Declaration of tuple variable with more elements will be long (imagine your example extended to T9;)
Yes, but it is only written once if it becomes a standard API
and used many times.
3. you can not use primitives.
You could write the combinations of Tuples for primitive
types, e.g. like:
http://trove4j.sourceforge.net/
Have done for Collections. It is a lot of work, but it is just
once off. You could cover boolean, char, int, long, float,
double, and generic Object up to T4 for example. Thats
a total of 7^4 = 2401 classes (so I would automate the
writting of them!).
Notes:
a. Only the classes you use get loaded
b. All the static creation methods could be called t
(for tuple) and the compiler will sort out which one you
mean.
c. The Trove people have successfully completed a much larger task.
d. Writting a tuple API will be **much** easier than
changing the compiler and JVM :)
Submitted On 26-OCT-2004
hlovatt
Oops I got my math wrong - it is:
7^2 + 7^3 + 7^4 = 2793 classes
Definatly automate the writing :)
Submitted On 27-OCT-2004
hlovatt
You can reduce the number of classes by not covering
every combination in every order, just covering every
combination in one order. e.g. for int (I), double (D), and
Object (O) up to 3rd order (Txxx):
TI
TD
TO
TII extends TI
TID extends TI
TIO extends TI
TDD extends TD
TDO extends TD
TOO extends TO
TIII extends TII
TIID extends TII
TIIO extends TII
TIDD extends TID
TIDO extends TID
TIOO extends TIO
TDDD extends TDD
TDDO extends TDD
TOOO extends TOO
Obviously this is a little more restrictive, you can
Submitted On 27-OCT-2004
hlovatt
not say T( double, int ) only T( int, double ). But on the other
hand the number of classes is greatly reduced. For 7 base
types to 4th order I think (!) the number of classes is:
(7) + (Sum( 1, 7 )) + (Sum( 1, 7 ) + Sum( 1, 6 )) +
(Sum( 1, 7 ) + Sum( 1, 6 ) + Sum( 1, 5 )) = 148
Note the Tx tuples and that the Txx tuples extend the Tx
tuples, etc. This allows you to drop unwanted return types.
Submitted On 28-OCT-2004
gnupun
Okay, so the tuples are type-safe compared to Object[] return value. But where is the return value description?
(a)
// what do the return values represent here?
Tuple3<String, Double, Double> getCurrentSatelliteLocation()
{
return new Tuple3<String, Double, Double>("new york", 40.77, 73.98 );
}
vs.
(b)
// return values clearly described
(String city, double latitude, double longitude) getCurrentSatellitePosition()
{
return ("new york", 40.77, 73.98 );
}
In case (a), you have to rely on comments to describe the return values. If comments are missing, as is often seen in the real world, you have to decipher it from the method's body.
Python has this problem in some cases where the return values are not described.
The tuple solution is also slow. In the tuple example (a) above, there are 3 unnecessary heap allocations: Tuple, Double, Double. It's also slower to retrieve the double values from the tuple than stack-returned values in (b).
The solution is simple: update the JVM spec so that methods are allowed to return multiple values on the evaluation stack instead of just one. This obviously affects the method signature format in the JVM and javac as well.
Submitted On 28-OCT-2004
gnupun
Okay, so the tuples are type-safe compared to Object[]
return value. But where is the return value description?
(a)
// what do the return values represent here?
Tuple3<String, Double, Double> getCurrentSatelliteLocation()
{
return new Tuple3<String, Double, Double>("new york", 40.77, 73.98 );
}
vs.
(b)
// return values clearly described
(String city, double latitude, double longitude) getCurrentSatellitePosition()
{
return ("new york", 40.77, 73.98 );
}
In case (a), you have to rely on comments to describe the
return values. If comments are missing, as is often seen
in the real world, you have to decipher it from the method's body. Python has this problem in some cases where
the return values are not described.
The tuple solution is also slow. In the tuple example
(a) above, there are 3 unnecessary heap allocations:
Tuple, Double, Double. It's also slower to retrieve the
double values from the tuple than stack-returned values
in (b).
The solution is simple: update the JVM spec so that
methods are allowed to return multiple values on
the evaluation stack instead of just one. This obviously
affects the method signature format in the JVM and javac
as well.
Submitted On 28-OCT-2004
hlovatt
The syntax for J5 generics using the tuple proposal above ,
would be:
TDDO<String> getCurrentSatelliteLocation()
{
return t( 40.77, 73.98, "new york" );
}
Pretty good eh!
Re. Efficiency. Not too bad, one tuple created because
primitives are supported. Also the tuple can be passed in
if you want to reuse them (see post above). Personally I
wouldn'y bother because object creation is quick enough.
Also this is a very narrow case of stack allocation, it would
be better to have a more general solution, e.g.:
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4617197
Re. the naming. That is meant to be the method name just like it is at present. IE at present you do not say:
String city getData( ... ) { ... }
You say:
String getCity( ... ) { ... }
Also, this convention of using the method name is
consistent with the naming of variables.
There is no issue at the callee end either. With multiple
return types you would say:
(final double lattitude, final double longitude, final String city) = getCurrentSatelliteLocation();
With my proposal you would say:
final TDDO lattLongCity = getCurrentSatLattLongCity ();
It seems a bit over board to want a new language feature
for something that is alreadt easy to do.
Submitted On 29-OCT-2004
gnupun
String getCity( ... ) { ... }
In this case, there only one return value whose meaning
is hinted in the method name (*city*). This syntax, however, does not scale well beyond one or two return values. That is, in multi-return methods, the method name is usually
useless trying to figure out which return value means what.
The J5 generics solution, while succinct, is extremely hard
to read. Consider applying J5 generics to input parameters:
(a) // regular java
int fooBar( int a, double x, String s ) { ... }
(b) // with J5 generics applied to input parameters
// not clear what the input parameters mean
int fooBar( TIDO<String> ) { ... }
While (b) is compact, it
Submitted On 29-OCT-2004
gnupun
While (b) is compact, it's readability is very low and would
frankly scare off any new Java programmer.
Which is better here -- (a) or (b)? I vote for (a).
Submitted On 31-OCT-2004
hlovatt
Hi,
(a) // regular java
int fooBar( final int a, final double x, final String s ) { ... }
(b) // with J5 generics applied to input parameters
int fooBar( final TIDO<String> aXS ) { ... }
You missed a vital piece of information on b, the argument
name! The only difference is the way type is specified, the
naming (i.e. the most useful bit) is the same. In both cases
the naming information is 'a', 'x', and 's' and if such short
names are OK for a then they are OK for b.
One of the reasons I am against adding this as a language
feature is that I think that it will reduce readability. The
satellite position example, whilst offered as a good use of
multiple return types in this forum, is I think better as a
class. IE:
// see below for why I extended TDDO
class Location extends TDDO< String > {
Location( final double long, final double latt, final String city ) { super( long, latt, city ); }
double getLatt() { return e1; }
double getLong() { return e2; }
String getCity() { return e3; }
}
So the reasons that I suggest a tuple API are:
1. The use of multiple return types is often shear lazzyness
and including them in the language would give this bad
practice (when used out of lazyness) some legitimacy.
2. You can achieve much the same with an API, so don't
burden every user of Java with a new feature for a small
gain for a few
3. The tuple API will encourage people to 'upgrade' to a
proper class that will be better, see Location example
above. IE to convert lazy code by refactoring into readable
code.
Submitted On 01-NOV-2004
jarouch
ad 1) Partially true, we are lazy to write useless code and maintain it. And it is good i think. Btw what do you think about new simpler and shorter aproach to EJB? Not-lazy people maybe like those ugly long configurations and so.. ;)
ad 2)
Lots of things can be done with API. In Smalltalk you have only API and it works too. Btw. people who dont want use it need not use it. It is same as with API. And other can have simple and efective way how to do it, what can bring benefits for rest of people. It is similar, as if some people argue against true multidimensional arrays or support for vector processing on modern CPUs, cause 'just few people use it'. But it can lead to faster swing and better fonts and ... for everyone.
Submitted On 01-NOV-2004
jarouch
Other good result of MRV - it is easier to manipulate with code.
Example - you want refactor long method. If you want remove part of it to separate method and this part modifies more then one local variable, you have problem, you can not pass context of method to another one.
Without MRV you create class holding part of this context or use some Tuple api, and replace block of code with call and N assignments.
Other possibility is write it all to one line and allow hotspot to inline removed part back easilly.
Submitted On 01-NOV-2004
hlovatt
Some points:
1. Lazyness - the use of multiple return types rather than a
proper class often is just lazyness. For example the satallite
position example is much clearer with a Location class.
Just like graphics are much clearer with a Point class. Also
note that a class, e.g. Point, can be used for input as well
as output.
2. There is more burden when you add a language feature
than adding an API. The API is just a class and people
already know about classes, the API will have a Javadoc
that explains hat it is and that the IDE can display.
This won't be true for a language feature.
3. There are probably some legitamate uses for a tuple API,
hence I proposed it. But there are not many uses that are
good. The area I have coded something similar to the tuple
API is for inside a class where private methods pass
multiple values between themselves. I could prabably be
persuaded that something with package access could be
a tuple. But I don't think there are any good examples for
tuple that are made public or protected.
If you can think of an example of when a tuple should be
made public, I would be delighted to see it :)
Submitted On 22-NOV-2004
dgreenbean83
I, for one, am enthusiastic about this RFE. Here are some uses that I would have for such a feature.
Say there is a class in the standard library: Tuple<A,B,C,D,...> where any number of types can be given, and that will determine the number of elements in the tuple. As for implementing this, it could be a special case reserved for this class in the standard library only.
Now, add some syntax to represent these tuples in a manner similar to how the RFE suggests: (a,b,c,d,...).
Say you want a method: (String,Point,JFrame) foo() {...}
which would be equivalent to: Tuple<String,Point,JFrame> foo() {...}
Say you have another method: bar(String s, Point p, JFrame f) {...}
Now, the language could interpolate this automatically to allow: bar(foo())
Of course, there would need to be a check that the first argument is not of type Tuple<A,B,C,D,...>, but that could be done at compile time.
If you consider the alternatives to doing this, you might end up with something like:
Object[] o = foo();
bar((String) o[0], (Point) o[1], (JFrame) o[2]);
The best workaround for this currently would probably be a wrapper class. Assuming, however, that there is little to no reason for grouping these three values together other than to pass them into bar, the Tuple<String,Point,JFrame> solution is just as intuitive, and does not require the programmer to keep track of yet another class.
If you really want a typesafe solution without adding this feature or creating a class each time you want to return multiple values, the only way I can see to do it is be defining a single class Pair<A,B>. From there, you could say:
Pair<String, Pair<Point, JFrame>> foo() {...}
bar(Pair<String, Pair<Point, JFrame>>) {...}
In this case you could say bar(foo()), but it is ugly and unintuitive.
As for not burdening people with another feature, the standard library has hundreds of classes that most people never use. Similarly, many people who use Java tend to ignore the fact that there are left/right shift operators and other language features that are just not as common as others. There are bad ways to use existing features in the language as well. People can write static classes when they shouldn't. People can also use deprecated methods in the standard libraries. I say that adding a new feature to the language is conceptually not very different from adding a package to the standard library. If people use it correctly, it can be very helpful and save a lot of time. If people misuse it, anyone editing the code will be very unhappy. This is true of any feature in the language.
Submitted On 25-NOV-2004
hlovatt
dgreenbean83,
Thanks for some of the best thought out comments re.
supporting this RFE. You have made a good suggestion
re. using tuples on input as well as output.
You can do what you want with the proposed tuple API:
<pre>
T3< String, Point, JFrame > bar() { ... }
...
void foo( T3< String, Point, JFrame > sPF ) { ... }
...
foo( bar() );
</pre>
Note with inheritance of tuples, as proposed, you can also
do:
<pre>
T4< String, Point, JFrame, String > bar() { ... }
...
void foo( T3< String, Point, JFrame > sPF ) { ... }
...
foo( bar() );
</pre>
Note: bar is now a T4 and it is passed as a T3 (T4 extends
T3).
RE Adding a language feature: it is more overhead than an
API; it isn't compatable with compilers, IDEs, pretty printers,
etc. and it is not documented by Javadoc. Therefore my
preference is to only add language features if there is a
good reason. From the example above you can see that
what you want is covered with an API. The syntax is
slightly different you need to type 2 extra characters (T3)
using the API approach. To me the saving of 2 keystrokes is
not sufficient for a new language feature. Further, if you
make something a language feature people tend to feel that
they should use it, even if the use isn't appropriate. For
some reason the "I must use it" feeling isn't as strong with
an API and I think therefoe an API is preferable for multiple
return types since there are many bad uses of this feature
and few good uses :)
Submitted On 28-NOV-2004
pmuurray@bigpond.com
The "deep thought" behind the language - that method cals are expressions, and an expression has a value - makes this very difficult. Would we need to look at n-ary assignment statements?
{
int foo;
int bar;
foo, bar = baz();
}
int, int baz() {
return 3, 4;
}
Submitted On 29-NOV-2004
hlovatt
Using a tuple library, as proposed in this forum, you could write
the above example as:
import static tuples.*;
class example {
public static void main(String[] notUsed) {
TII fooBar;
fooBar = baz();
}
TII baz() {
return t(3, 4);
}
}
Is it really worth a language feature for so little difference?
Submitted On 07-DEC-2004
gepardpro
Holders for Corba, Holders for RPC, special support for EJB Web Service etc. It is crazy that Java hasn
Submitted On 14-DEC-2004
willisboyce
I'm really surprised that it took over five years for someone to bring up the obvious problem with this request as written: it addresses only the case of assigning the multiple return values to multiple variables and doesn't take into account how MRV functions would work within expressions.
If (int,int) creates an anonymous class behind the scenes, then that implies that function(int x,int y) and function((int,int) xy) are two different functions. Calling function(a,b) would invoke the first while calling function((a,b)) would invoke the second. How would that make the language clearer? Do we really need more than one way to pass two ints to a function?
Some people have noted that if (int,int) creates an anonymous class, then it becomes little more than a syntactic shortcut. I agree. But if it doesn't create an anonymous class, then it becomes impossible to use a MRV function as part of any expression other than an assignment. It seems strange to have special support for a functions that return values but can't be used in expressions, since the whole point of using a return value, as opposed to an "out" parameter of some kind (in languages that support "out" parameters), is so the return value can be used in an expression.
Furthermore, no one has brought up the potential for this feature to create nightmare code. Having a function return (int,int) is convenient, sure. But it would be just as easy to return a (int,int,int,int) instead of a Rectangle instance, or a (String,String,Rectangle,Socket,ResultSet,GZIPOutputStream) instead of something that actually made sense.
IMHO the best overall way to handle multiple return values is to create a result class of some kind. Having to create a new instance of the result class every time isn't really a problem. Anyone who's run a Java program under a memory profiler knows that the JVM creates objects like crazy, all the time. In my own web application, the application server's JSP code and the database drivers generate one or two orders of magnitude more garbage than my own application. Having to create a new instance of the result class every time is only an issue if the code invokes the function enough to turn it into a bottleneck, and in nearly all of those cases, simply allowing the caller to pass in an existing instance of the result class will eliminate the bottleneck.
Given the above, and given that neither the AWT nor Swing, which return Point, Dimension, and Rectangle instances all over the place, conspicuously suffer from their inability to return (int,int) or (int,int,int,int), I think that the case for this request seems pretty weak.
Submitted On 13-JAN-2005
Quartz
This whole request is ridiculous. First, someone pointed that C could change the values and Java could not. Try:
private void inc(int[] valuesToBeIncreased) {
for (int i; i < valuesToBeIncreased.length; i++) {
valuesToBeIncreased[i]++;
}
}
Similarly, you can use mutable objects if they have to be changed inside. Works better than having to change damn pointers and kill your program because you forgot an * somewhere.
This request goes along with the "CONST" RFE as the 2 "workarounds for bad designers".
Submitted On 01-FEB-2005
vjave
Why are multiple return values any "worse/confusing" than multiple arguments? Does input not need to be OO, but output does? How about a RFE to restrict all method to exactly one argument? We
Submitted On 01-FEB-2005
vjave
Why are multiple return values any "worse/confusing" than multiple arguments? Does input not need to be OO, but output does? How about a RFE to restrict all methods to exactly one argument? We have gone the other way with varargs.
Submitted On 01-FEB-2005
hlovatt
I think in a well designed API you wouldn't have lots of arguments to methods in general. The disadvantage of multiple reurn types is that people will get lazy and instead of Point they will use (int, int) and this will spread to the input as well so that instead of distace( Point, Point ) we will get distance( int, int, int, int ), clearly the first is better and the second should be discouraged.
So in summary I think Java has it right, you need multiple arguments much more often than multiple return types so provide them. But don't provide multiple return types because people are basically lazy and the code quality will drop as a result.
In any case, if you really want multiple return types use a Tuple API like other languages do, e.g. Haskell.
Lets re-phrase you question, whats wrong with a Tuple API?
Submitted On 08-FEB-2005
rcengels
using a 'return' class also alow for MUCH easier refactoring/inspector, since using a modern IDE can easily see all uses of a particular class - try that with (int,int)...
Submitted On 09-FEB-2005
jarouch
rcengels: yep, and petrol cars are much better then hydrogen ones, because petrol pump is at every corner :)
Submitted On 14-FEB-2005
hlovatt
I think rcengels is making a good point. If we had a Complex class as oppossed to (double double) and a Point class as opposed to (double, double) then using classes is both clearer for the programmer and for the support tools. For both the programmer and the support tools distinguishing between one use of (double, double) to another use is difficult.
Submitted On 15-FEB-2005
renkrad
A simple question :
How would you refer to the returning values of the
Submitted On 15-FEB-2005
renkrad
MY COMMENT WAS CENCURED!!! :|
A simple question :
How would you refer to the returning values of the following example?
public static (int, int) swap(int a, int b) {
return (b, a);
}
(Hope this time the Men in black aren't aroun to censur my post :|)
Submitted On 16-FEB-2005
jarouch
In such case (one Complex number) yes. But still can be usefull to have algorithms over Complex numbers implemented for generic pair of float/double .. it lets us use one piece of code at many places.
example - you have Complex which implements method mul(Complec c), and you have ComplexVector, which behaves like vector of numbers, but has another, efective internal structure, implementing mul(Complex c) = mul each element of .. . And you have ComplexMatrix and ComplexCube .with similar mul() method. With MRV you can easily imlement method
(float, float) complexMul(re1, im1, re2, im2)
and use it in each of those structures. In other case, you have to have N implementations of same functionality.. Or one, implemented with Complex, but it will lead to lots of temporary Complex-es..
And if you once would like compute complex multiplication between Vector2D-s, you could easily add method wrapping
new Vector2D(complexMul(v1.x, v1.y, v2.x. v2.y)) ;)
Btw. there are cases, where we need not store 'tuple' of values, just move them. Example - you have BIIG method and you want to refactor it.. OK, let take part of it , change it to another method and replace code with one call. But what can we do, if this part of code changes more than one external value? We will need some ContextOfCall, or ChangesWrapper, with just one purpose...
Submitted On 16-FEB-2005
jarouch
renkrad
do you mean something as
(a, b) = swap(a, b)
???
Submitted On 16-FEB-2005
hlovatt
In reply to jarouch ,
Nothing to stop you doing what you want with a Tuple API, see this forum for a suitable design. Why add a language feature when we can already do it?
Submitted On 17-FEB-2005
jarouch
Idea of Tuple API is nice, but it solves just one part of MRV - we need not to write wrapper. Its fine, helpfull, but you need still
instancialize tuple - it brinks overhead
unwrap values from tuple - more lines of code, worse readibility, next overhead, because you have to fill tuple and unroll it back instead of direct copy..
i still think that
(x, y, z) = f();
is more readable then
TFFF pom = f();
x = pom.getV1();
y = pom.getV1();
z = pom.getV1();
(even if the second is much better then class MyOnceUsedWrapper { ... ;) )
What should be the solution (i hope it is not higher in text:) ) -
1) add Tuple API (will be helpful alone..)
2) add syntax sugar looking like MRV = unboxing tuple to list of variables/parameters and back..
3) make Runtime to recognize it as Well Known Pattern which can be optimized and proceed directly without instantialization overhead.
So it will run everywhere and at good runtime will be optimal..
Submitted On 24-FEB-2005
hlovatt
Stack allocation of multiple-return values is a very narrow case of stack allocation, it would
be better to have a more general solution, e.g.:
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4617197
Wich is an RFE for immutable types. An immutable Tuple would be stack allocated and immutables have many other uses. Also see the pattern enforcing compiler (PEC):
https://pec.dev.java.net/nonav/compile/index.html
Which supports the Immutable pattern.
Submitted On 03-MAR-2005
AlexLamSL
In my opinion, defining a few variants the following object in J2SE 5 "Tiger" would have helped a lot people who likes this "Multiple Return values":
public class Doublet<A, B> {
private A a;
private B b;
private boolean readOnly;
public Doublet(A a, B b, boolean readOnly) {
this.a = a;
this.b = b;
this.readOnly = readOnly;
}
public Doublet(A a, B b) {
this(a, b, false);
}
public A setA(A value) {
if(readOnly)
throw new IllegalAccessException("Read-Only!");
A o = a;
a = value;
return o;
}
public B setB(B value) {
if(readOnly)
throw new IllegalAccessException("Read-Only!");
B o = b;
b = value;
return o;
}
public A getA() {
return a;
}
public B getB() {
return B;
}
}
As many would want to argue, defining this with Triplet and Quarduplet for instance, would not be the general way to solve the problem; I totally agree with such sayings, but do bear in mind one fact - "multiple return values" gets really unfriendly if you have n > 3, at which point I hope I can convince most of you that defining a seperate class helps.
As of the talk about Java experience - I haven't got a personal line counter, so I'd just be very humble in submitting my little suggestion =P
Submitted On 17-MAR-2005
bvarnerumc
I would argue that if you need more than one return value, you're doing a piss poor job of utilizing or understanding OOP.
While I also understand that in some cases this may be an overreaching generalization, I get the feeling you're forgetting that objects have state, and you're stuck in C-mode of thinking.
Get overyourself, I've been working with java for well over five years, (so obviously I have some expirence) and have never run into a case where a single return value has been a 'limitation' or bottleneck.
Submitted On 21-MAR-2005
AlexLamSL
bvarnerumc, although I don't this idea, I'm afriad I'd have to question your argument - what has
Submitted On 30-MAR-2005
Falko@home
-1 vote from me. One needs this allmost never. Who is afraid of creating objects should take another language.
Submitted On 01-MAY-2005
pmuurray@bigpond.com
Constructing small return value objects is not that inefficient. Fixing this requires altering the whole idea of a
Submitted On 01-MAY-2005
pmuurray@bigpond.com
Anonomous classes. These would be "owned" by the system in the same way that array classes are.
class A {
{int a; String b;} foo(Object o) {
return new (1, "Hello");
}
void bar() {
{int a; String b;} ret = foo(null);
print(ret.b);
}
}
Submitted On 07-MAY-2005
jonathanfinn
This has been marked 'Closed, will not be fixed'.
I'm not very impressed by the evaluation that multiple return values would be better expressed by returning a single object.
By this argument, methods should only be allowed to take 1 parameter, since several parameters could always be packed into a single object. The fact is, parameters are often logically independent so you'd have to create an ad hoc class to pack the values into, and this class would likely only be used in 1 place, adding to complexity.
As far as I can see, the same argument applies to return values. I don't see why methods shouldn't often return several logically independent results, when packing them into a single object would just increase complexity, not decrease it.
The example of Point instead of (int,int) used in the evaluation is specious. The purpose of this RFE is to simplify methods which return results that are *not* closely related, so there is no reasonable class to pack them into. (This is a classic example of 'straw man' argument: disproving a stupid point that was not the point that was originally made.)
We can all accept proposals being rejected for good reasons - such as technical problems, lack of resources, etc. But not evaluations based on naive arguments.
Submitted On 07-MAY-2005
jarouch
Sorry, but big part of comments is about showing that implementation of MRV is possible WITHOUT changes in JVM. Maybe we all are wrong, in such case - could you, please, explain, where is the problem?
MRV don't break static character of language. In my (subjective) opinion, MRV are clean and intuitive to use. In contrast to new features like generics, autoboxing and static imports, which are usefull sometimes but bring strange behaviour in other cases. One of them is they can go directly against readibility, which is mentioned as problem of MRV..
In case of Point, you are right, but every usecase of MRV is not Point-like..
To compare using of the other features in JDK with MRV is not correct, I think. It is the same as to say in time of JDK 1.4 - we need not generics, because, compared with other features added sooner and extensively used ... .
Submitted On 07-MAY-2005
blbrown
I was surprised, this was submitted 6 years ago and I can only imagine the number of people wanting this feature and you dropped it? Wow. To the earlier post, I would see MRV used way more compared to generics.
Can you give us lambda instead? Functions that return functions?
Submitted On 08-MAY-2005
jonathanfinn
Re this new addition to the evalution:
> As a matter of programming style, this idea is not
appealing in a object oriented programming language.
Returning objects to represent computation results
is *the* idiom for returning multiple values. Some
suggest that you should not have to declare classes
for unrelated values, but neither should unrelated
values be returned from a single method.
Yes, I've heard this argument that the 'OO' way to return multiple values should be to return a single value from each of multiple methods. This makes sense for some types of methods, such as getters. But what if the method performs some calculation (which doesn't just involve changing the state of the object), and returns the results of the calculation? This can't conveniently be split amongst several methods, because the methods would have to be called in a magic order, starting with the one that actually performs the calculation, with mayhem if you get the order wrong. As an alternative we're back to a single method call returning results packed into a special class, so you can call getters on that class. But often (I contend) such a class would be completely ad hoc, making this just a hack.
Now some will argue that real-world examples are rare. Perhaps, but it's difficult to tell whether we would use an idiom which is currently denied to us. I can't accept that it's not a natural and logical idiom; but I can accept that it would involve too much work to implement it in the JVM.
Submitted On 09-MAY-2005
jarouch
So do I understand well, that proposal to add tuples or record types are acceptable for you? It is nice, you welcome new proposals, question is if it does have sense to send them..
Maybe you should declare some range of acceptable changes, to avoid people from sending useless requests you close after years, tons of talk and given votes..
Submitted On 09-MAY-2005
intangir2
I don't agree with evaluation, but in my opinion this is less urgent than the following performance RFEs:
1. 4809540 - Objects in stack.
2. 4820062 - Structs in Java.
3. 6206009 - Desktop applications.
4. 4990597 - Lighter soft references.
Submitted On 02-AUG-2005
AJohnB
the reasons why not are rather glib. you could just as easily argue that multiple parameters aren't required. There is a symetry between parameters and results and all of the arguements for multiple typed parameters apply equally well to multiple results.
Submitted On 07-JAN-2006
cobe
I can only say that I've been writing Java code for 10 years and have often found myself wishing for this feature. It was #2 for me after generics. Of course you can always work around it, but there are many cases where one ends up defining a one-time class to return two or more separate products of a single computation. I completely agree with AJohnB that most of the arguments against MRV could just as well be used against multiple parameters.
This feature is not a kludge. From a pure (math) point of view, isn't it inelegant to impose restrictions on a function's range but not its domain?
The only strong (but unfortunate) reasons I see for not including it are a) it may be too late to incorporate such a low-level change into Java, and b) over the last 50 years most programmers seem to have gotten used to getting by without it. But I predict that in the next 10 years programmers will move past these excuses.
Submitted On 12-JAN-2007
rami
ramimahdi@yahoo.com
this feature must be added because it saves alot of time doing stupid redundant meaningless stuff
and all the arguments against it makes no sense
I guess I am going to abandon java some time very soon
Submitted On 16-AUG-2007
fast40xb
James Gosling, the creator of Java, said in July of 2000:
"There have been a number of things -- like, for example, multiple return values -- that these days I kind of wish I had added. " link: http://www.gotw.ca/publications/c_family_interview.htm
What makes this frustrating, is obviously this would be helpful, and it's been identified over 7 years ago, even by the creator of Java itself.
Detractors argue that data that belongs together should be in a class anyway. And if the data doesn't belong together, then the method should not return the data together. This is oversimplification. Most of the time, the reason for returning multiple pieces of data is that they are related, but they don't belong in the same object. Maybe a value object and a status flag about the object. Maybe a collection of objects that needs further processing-- especially if the objects are of different types.
You can use an Array, List or Map to return the values, but doing that prevents static typing, one of Java's great benefits.
An example of the syntax I would like to see is:
public (boolean status, StatusDoesntBelongInMe valueObj) specialMethod (String inParam);
The difference in this example from before, is I named the output parameters. These are helpful for IDE's to provide context clues and advice to the programmer. Calling the method would still look like:
(status, obj) = specialMethod ("test");
If we can have generics and enums in Java, then I don't see any reason not to have multiple return values.
PLEASE NOTE: JDK6 is formerly known as Project Mustang
|