Skip to main content

Pass by reference - why not?

68 replies [Last post]
u5321007
Offline
Joined: 2003-08-06

first forgive my poor English. I am not native speaker.

I know without pass by reference , java still can do a lot of works. But it make me hard to port C++ code to java. And most large C++ framework use pass by reference a lot.

For example, *IF" java suport pass by reference, I can write this:

void get(Object owner, int type, int& index, BaseTable& tbl )

since java *DONT* support pass by reference, I can only write in these two ways

(1)
void get(Object owner, int type, Object[] refArgs )
{
...
refArgs[0] = xxx;
refArgs[1] = yyy;
}

when we use this method, we need do like this

Object[] refArgs = new Object[2];
base.get(this, smvShape, refArgs)

(2)

Object[] get(Object owner, int type){
...
Object[] refArgs = new Object[2];
refArgs[0] = xxx;
refArgs[1] = yyy;
}

I feel this is ugly, and allocate small object array will slow the performance when this function call is the bottle neck.

Any idea of why java doesn't support pass by reference? I need a strong reason to let me don't feel so frustrated while porting C++ code.

I do really hope it can support in mustang or dolphin.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
kcpeppe
Offline
Joined: 2003-06-15

>
> Why do keeping running arround the core problem and
> you don't want to confess that there is a need to
> have a handy way to get it done in a readable
> fasion.

Because it my almost 20 years of doing OO, I have never run into a case where I needed to return a tuple as you seem to need to.

>
> saying that there is no cases where should I return
> multiple values out of a function is poll shit. You
> are not god to say such a thing. Also a strong
> Language should handle all the possible cases in
> perfect ways, not in such stupid workarrounds.

Ok, you need to tone down your language!

public class C {
int x=1;
public C() {}
public static void fooc){ c.x=10; }
public static void main(String[] args) {
C c = new C();
foo;
System.out.println(c.x);
}
}

This example doesn't compile so I don't know how you can claim the output that you got unless you are a troll or you really meant this;

public class C {
int x=1;
public C() {}
public static void foo(int c){ c.x=10; }
public static void main(String[] args) {
C c = new C();
foo();
System.out.println(c.x);
}
}

If this is what you mean, then we are not only dealing with a case of pass-by-value but also variable scoping and visability. You have declared one instance variable which has package visability (not that would matter much in this case as if it were private, you'd see the same result). Now you are passing into a static method a value (pass-by-value) to which you are making a direct assignment to a variable with instance level visability (for every class in the package). In other words, this example is very confused and the assignment will stick and the rules governing this are quite regular and well known. Java must work this way or you'd never be able to get things done.

Here is another example

public class C {

int x;
public C( int initialValue) {
x = initialValue;
}

static void foo( C c) {
c = new C( 10);
}

public static void main(String[] args) {
C c = new C(2);
foo( c);
System.out.println(c.x);
}
}

The output from this example is 2. Another example....

public class C {

static void foo( int x) {
x = 10;
}

public static void main(String[] args) {
int c = 2;
foo( c);
System.out.println(c);
}
}

Same result, output is 2. The value for x is placed on the stack and those "changes" are made locally and lost when the stack unwinds. Note, if you wrote this code in C, you'd see the exact same results.

jwenting
Offline
Joined: 2003-12-02

>
> (boolean, int) Integer.parseInt(String s);
>
> which needs not an (slow and memory eating)
> allocation and (slow) throw Exceptions. Of course,
> we can wrap it to one
> JustOnePurposeClassWhichSomeoneHadToWrite and create
> more and more useless objects.
>
Learn to do value checking before you call such functions.
If you pass a wrong value you get an exception, that's how the language is designed.
A better option to avoid exceptions in situations like this is to pass a null value in case of failure, as is common in C.
But that's not the way Java is designed, exceptions being far cleaner.

> No, the (current) escape analysis does not help us,
> the parsing method is big and it will never be
> inlined..

Learn to use the exception handling mechanism properly or use another language.

hlovatt
Offline
Joined: 2003-11-18

@jarouch

> It could be changed to much better
>
> (boolean, int) Integer.parseInt(String s);
>
> No, the (current) escape analysis does not help us,
> the parsing method is big and it will never be
> inlined..

The escape analysis in 6 does not depend upon the size of the method only the use of a variable (also it does not inline methods it stack allocates objects). So in 6 using a tuple libraray or a specific class, it is likely that no object will be allocated on the heap. Therefore there is little advantage in multiple return types over say:
[java]
T2< Boolean, Integer> Integer.parseInt( String s ) { ... }
[/java]
Personally I think Sun are spending their time wisely in 6. They have not just added every possible feature, instead they have spent there time on an optimisation, escape analysis, that will benifit many.

jarouch
Offline
Joined: 2004-03-04

Realy? Do you have any document/url about it, please? In texts I saw before it looks like it can optimize (allocate on stack) returning object just if the called method is inlined to the caller. If Mustang realy could allocate on stack objects returned through levels of calls, or allocate just used fields of object/map them to another used variables, it would be realy very similar in result.
Of course, package with tuples and some syntax suger icing would be helpfull too;)

hlovatt
Offline
Joined: 2003-11-18

Escape analysis is breifly described here:

http://www-128.ibm.com/developerworks/java/library/j-jtp09275.html

A much more detailed paper is:

http://www.research.ibm.com/people/g/gupta/escape.ps

The later says: "If an object does not escape a method, it can be allocated on the method's stack frame" and this is not qualified with provided the method is inlined, therefore my reading is that a tuple class could be stack allocated by J6.

On the subject of a Tuple class, you don't need to wait for an official one. Write your own, its easy!

Back to the first paper above, this paper also shows that heap allocation is nothing like as expensive as many people assume. So I think you will find that even with J5 returning tuples will be fine.

ramimahdi
Offline
Joined: 2004-05-29

I have tried the following code
public class C {
int x=1;
public C() {}
public static void fooc){ c.x=10; }
public static void main(String[] args) {
C c = new C();
foo;
System.out.println(c.x);
}
}

then what was printed is 10. So tell me. Does java pass by refrence or by value. I think it does pass by reference the objects. but pass by value the primitive data type.

So, in contrary to what is being claimed that sun did not make it possible to get multiple values out of a methode for making us do perfect OO and our design is bad is poll shit.

Becuase by priniciple sun is allowing us to pass objects by refernce to methods and hence get multiple values out of the method.

So, it is just a matter of the primitive data types. Also if I want to use the stupid Integer class to get two int values out of a method, unfortunately it doesn't contain setValue method. Even if does contain such a method, my code will look really ugly.

Also, if you say that that Tuple class will solve my problem. Why not sun standarize such a method and make it easier and more compact to use on the fly.

I beleive sun in this respect is self-contradictory

ramimahdi
Offline
Joined: 2004-05-29

There is one more thing I want to add to my last contribution.

I think the given Tuple class doesn't solve the problem. Because It handles two return values. But what if I had three, four and five.
Should I write a class for each. That is really silly.

If there is such a class Tuple who will solve my problem It should be a standarized one because I don't want to add classes to my application that has nothing to do with the business of my project.
Also this stadanrized class should take care of all the cases (two, three ...... or what ever number of output parameters).

subanark
Offline
Joined: 2004-11-26

If you really want to have "out" parameters, the simplest solution is to use arrays of size 1. E.g.
public void getTime(int[] seconds,int[] minnutes,int[] hours)
{
int diff = start-System.currentTimeMillis();
hours[0] = diff / (1000*60*60);
diff %= 1000*60*60;
minnutes[0] = diff / (1000*60);
diff %= 100*60;
seconds[0] = diff / 1000;
return;
}

And so far as a class that supports Truples and everything else, use a Map. You can use some generic tricks to get it to return the correct return type.
E.g.
public interface IdentifierMap
{
K get(Identifier key);
void put(Identifier key, K value);
}
public class Identifier
{}

ramimahdi
Offline
Joined: 2004-05-29

I cannot do it and return array of int[] to get out two irrelated. Because I cannot watch my code being such ugly and so much ir-readable. I cannot believe that you have a sense of well engineered coding.

Why do keeping running arround the core problem and you don't want to confess that there is a need to have a handy way to get it done in a readable fasion.

saying that there is no cases where should I return multiple values out of a function is poll shit. You are not god to say such a thing. Also a strong Language should handle all the possible cases in perfect ways, not in such stupid workarrounds.

jwenting
Offline
Joined: 2003-12-02

Why don't you learn proper software design and writing instead of insisting that Sun change their language to fit your corrupted idea of how the world should work?

tackline
Offline
Joined: 2003-06-19

So, how should BigInteger.divideAndRemainder have been written? Should it not be present, leaving the client code to write the same operation twice? Or perhaps introduce a new type specifically to store a BigInteger quotient and remainder. Or just a Pair type.

http://download.java.net/jdk6/docs/api/java/math/BigInteger.html#divideAndRemainder(java.math.BigInteger)

I think multiple return preferable to dealing with unpacking of results.

It's instructive to look at basic mutable value classes. In normal terms, a set never changes. Just like a string. However, for reasons of efficiency and because of deficiencies in Java, java.util.Set is mutable. You can think of it as having an assignment back to the original object after every operation. An immutable version of Set makes sense. Unfortunately methods such as add and remove require two return values.

kcpeppe
Offline
Joined: 2003-06-15

> So, how should BigInteger.divideAndRemainder have
> been written? Should it not be present, leaving the
> client code to write the same operation twice? Or
> perhaps introduce a new type specifically to store a
> BigInteger quotient and remainder. Or just a Pair
> type.

ahh at last a good example. Should the operations be performed seperately or should the results be pulled apart? IMHO, the answer to this question is yes and here is why. You are clearly asking two different questions of the BigInteger, the execution two different queries. The calculations for each need to be performed seperately and need to be treated seperately. Combining is not a mixing of concerns (the opposite of seperation of concerns one of the goals of OO). So this is a request for language features that don't really support OO design. If there is a relationship between the results of the queries, then that relationship will be represented by a Class in your domain. It is always more desireable IMHO to maintain a good seperation of concerns then it is to avoid finding key elements in your domain.

>
> http://download.java.net/jdk6/docs/api/java/math/BigIn
> teger.html#divideAndRemainder(java.math.BigInteger)
>
> I think multiple return preferable to dealing with
> unpacking of results.
>
> It's instructive to look at basic mutable value
> classes. In normal terms, a set never changes. Just
> like a string. However, for reasons of efficiency and
> because of deficiencies in Java, java.util.Set is
> mutable. You can think of it as having an assignment
> back to the original object after every operation. An
> immutable version of Set makes sense. Unfortunately
> methods such as add and remove require two return
> values.

Why should a set never be mutable? I think this is a very narrow definition of set, don't you?

jwenting
Offline
Joined: 2003-12-02

And if you insist on having unmutable sets you can already extract them from regular ones using Set Collections.unfodifiableSet(Set s) which is a standard library function in the collections framework...

tackline
Offline
Joined: 2003-06-19

Collections.unmodifiableSet isn't particularly helpful as a set. You cannot (directly) perform set operations upon it.

jwenting
Offline
Joined: 2003-12-02

Gosh, it's a readonly set and you can't modify it...

Exactly the point I was trying to make as to why readonly sets are usually useless :)

tackline
Offline
Joined: 2003-06-19

Gosh, String is a readonly string and you can't modify it...

Someone should remove all the string operations on String as they are useless. ;(

jarouch
Offline
Joined: 2004-03-04

One real life example of returning related values -

int Integer.parseInt(String s) throws NumberFormatException

and other equivalent methods.

It could be changed to much better

(boolean, int) Integer.parseInt(String s);

which needs not an (slow and memory eating) allocation and (slow) throw Exceptions. Of course, we can wrap it to one JustOnePurposeClassWhichSomeoneHadToWrite and create more and more useless objects.

No, the (current) escape analysis does not help us, the parsing method is big and it will never be inlined..

kcpeppe
Offline
Joined: 2003-06-15

> One real life example of returning related values -
>
> int Integer.parseInt(String s) throws
> NumberFormatException
>
> and other equivalent methods.
>
> It could be changed to much better
>
> (boolean, int) Integer.parseInt(String s);
>

But this is an exception which shouldn't be happening all that often or if it is, then by definition, it's not an exception. Better to fix the deeper problem then hide it with syntax.

sjasja
Offline
Joined: 2004-08-15

> I have realy very simple and silly question.
>
> Should I be expert OO engineer to be able get two
> irrelated values out of a function.

Can you show us some genuine real-life situations where an expert OO engineer would write methods that return unrelated values? Some kind of a situation that occurs often and cannot be handled by real OO programming style?

I'm sure it happens though I can't recall it happening to me. So I'm intrigued by the circumstances under which it keeps happening all the time to some expert engineers.

tsinger
Offline
Joined: 2003-06-10

I'm working on a geodetic application for a long time. Often coordinates are paired (e.g. north and east). Having two methods, one for each axis would be very bad, because then often a calculation would be necessary a second time.

But I don't understand the need for defining a method which returns two or more values, because we already can do something like that:

[code]public interface Coordinate {
double getNorth();
double getEast();
void setNorthEast(double north, double east);
}
...

public void calculateSomethingUseful(Coordinate target) {
...
final double north = ...
final double east = ...
target.setNorthEast(north, east);
}[/code]
Where is the problem?

Tom

hlovatt
Offline
Joined: 2003-11-18

@ramimahdi,

In an non-OO language there is a much stronger case for multiple return values, but once you have OO it seems like a feature of less value. EG consider a graphics library, in a non-OO language you would be always return X and Y integers, but in an OO library you would make yourself a Point class. So your options in Java, in probably order of preference, are:

1. Make a class and return an instance of it, e.g:
[code]
class Point {
int x;
int y;
Point( int x, int y ) { this.x = x; this.y = y; }
}

Point foo() {
....
return new Point( x, y );
}
[/code]

2. Use a tuple library with a static import, e.g.:
[code]
class Tuples {
...
static class T2< E1, E2 > {
E1 e1;
E2 e2;
Point( E1 e1, E2 e2 ) { this.e1 = e1; this.e2 = e2; }
}
static < E1, E2 > T2< E1, E2 > t( E1 e1, E2 e2 ) {
return new T2< E1, E2 >( e1, e2 );
}
...
}

import static Tuples.*;
...
T2< Integer, Integer > foo() {
....
return t( x, y );
}
[/code]
Neither solution is exactly long and most people feel that the first solution reads particularly well!

jwenting
Offline
Joined: 2003-12-02

And if you require multiple return values anyway, just return an array of Objects...
Tough luck on not getting compile time type safety, but that's a consequence of your design decisions.

tobega
Offline
Joined: 2004-06-20

> So here, I peg for somebody to tell me how to get
> multiple (int) values that are unrelated out of a
> method in handy way.

If you are getting multiple unrelated values out of a method, you have a SERIOUS problem in the design of your code....

Trying to make Java more like C is totally breaking the whole idea of Java, especially when you start talking about pointer-like constructs. I would rather go the other way, i.e. even Objects passed as parameters should not be allowed to be modified (at least not without a compiler check that the caller understands this will happen)

podlesh
Offline
Joined: 2004-07-26

> I hope that the top management of sun could hear me.
> becuase i want to tell them to wake up. and go read
> what microsoft is planning to launch for .NET 3 (C#3).

Oh no, please!
They already tried to copy feature (autoboxing) and result is... bad.

kcpeppe
Offline
Joined: 2003-06-15

> When first I read about C# and found the pass by
> reference of the primitive arguments (i.e. int ..),
> it really did touch my heart. The reason is that I
> have made alot of programs in java where i need to
> get multiple parameters out of a method.

I challenge your designs if this is the case. I've never felt the need to pass back multiple arguements either in an array or in meaningless objects.

Pass by reference is a valid programming model. That said it is not the Java programming model. To switch the Java programming model to pass by reference would break many things. Pass by reference is not safe and precludes one from making many of the assumptions that result in many of the speedups that we see from hotspot. Pass by reference may even break current GC. So this is not a matter of let the programmer decide.....

I've also worked with a single language that allowed you to return two values in one operation. It was ok but really only used in edge cases. General purpose languages shouldn't cater to edge cases. I'd recommend that you use another language if you find yourself in that situation.

jwenting
Offline
Joined: 2003-12-02

> #1 It is not your problem and won't affect you. If
> mutiple return parameters are added to Java, why do
> you care?

It WILL affect me, simply because it's there.
Some idiot (like you) will abuse it and I'll be saddled with the responsibility of undoing the damage.
Quite possibly the very existence of the feature might also break code I wrote in the past, causing even more work.
So even if I don't intend to use it I will have to know about it and keep it into consideration, as well as clear up the mess it causes.

> #2 A repeating theme I keep reading is that multiple
> return parameters are not a proper object oriented
> solution. Our job as software developers is not to
> come up with proper object oriented solutions, it is
> to meet our clients' software requirements. Object
> oriented programming is one of many useful

And proper OO techniques help achieve those goals and requirements with less effort than flounting them like you intend to do.
When needed we all leave the beaten track, but we don't do so simply because it sounds like a good idea at the time.

> #3 There is a very small but significant overhead in
> creating small objects just to shuttle values back
> and forth from function calls. In 90% of programs
> that overhead make no difference whatsoever. In the
> remaining 10% that deal with processing large data
> volumes, very high throughput, need very quick
> response times or do intensive number crunching, it
> makes a significant difference. If you are not doing
> that kind of software development then multiple
> return parameters are not applicable to you.
>
If you're having to rely on something that doesn't exist you're using the wrong tool.
Are you also complaining to hammer manufacturers for not providing hammers that can be used as screwdrivers?

> Please stop insulting others by telling them that
> they are not doing "proper" object oriented design.

We don't insult anyone.
If you feel insulted by us not agreeing with you that's your problem, not ours.

> In my own case I could not care less about "proper"
> " design, I care about giving my clients stable,
> correct and maintainable solutions that meet their
> requirements. OO design is one of the many tools I
> use to do that.

Without properly designed systems your clients will sooner rather than later feel the consequences of your actions in high failure rates.
If you don't want to use OO, use a non-OO language like C or Fortran.

rogerhernandez
Offline
Joined: 2005-02-23

Why do you resort to insulting others instead of using valid technical points in your arguments? It is usually the sign of an insecure person. Please do not respond, since I will be ignoring all your messages from now on.

sjasja
Offline
Joined: 2004-08-15

> Why do you resort to insulting others instead of
> using valid technical points in your arguments? It
> is usually the sign of an insecure person. Please do
> not respond, since I will be ignoring all your
> messages from now on.

I don't know to whom you are responding, but:

Do you see the irony of making an ad hominem attack and an "I won't play with your toys any more" threat?

If someone disagrees with you, he disagrees with you because he disagrees with you. Not because there is some great conspiracy to insult you. Please note that so far you are the only one to drag the conversation into "insulting" and "insecurities" of other people.

Peace, dude. Chill. Standard relaxation recipe: a martini + a BJ.

mcnepp
Offline
Joined: 2005-06-22

> I don't know to whom you are responding, but:
>
> Do you see the irony of making an ad hominem attack
> and an "I won't play with your toys any more"
> threat?

He was obviously responding to jwenting who had definitely lost good manners before and was getting really nasty in his latest post.

jwenting
Offline
Joined: 2003-12-02

So now saying that you have problems if you think you're being insulted when you're not is nasty?

Hmm, weird things have happened to society lately...

Noone is insulting him, but he seems to think to.
Is it our problem if someone thinks that disagreement with his ideas is an insult to him?

podlesh
Offline
Joined: 2004-07-26

> Hmm, weird things have happened to society lately...
Yes, really weird. Calling someone "idiot" was always considered insult, as far as I remember.

This discussion is lost in flames.

rjlorimer
Offline
Joined: 2003-06-10

Podlesh - I agree. While I generally agree with the sentiment from 'jwenting', the use of agressive, angry posting in conjunction with name calling (neener neener) such as idiot is not exactly... constructive.

ramimahdi
Offline
Joined: 2004-05-29

When first I read about C# and found the pass by reference of the primitive arguments (i.e. int ..), it really did touch my heart. The reason is that I have made alot of programs in java where i need to get multiple parameters out of a method. It is nasty design and code to pass array of object or get the outputs or create a meaningless class just to combine those parameters and return object of this class.

I believe that those that are againist pass by reference or multiple outputs had never involve in writting serious programs.

It is really killing me when I am stuck in its need.

So here, I peg for somebody to tell me how to get multiple (int) values that are unrelated out of a method in handy way.

This debate is the same as the debate of operator overload. Why not sun just put us (the programmers) these options and leave it to us either to use or not.

I beleive that the JDK top engineers are old people who are stuck to the old days of programming and follow a conservative approach in developing java.

I hope that the top management of sun could hear me. becuase i want to tell them to wake up. and go read what microsoft is planning to launch for .NET 3 (C#3).

sjasja
Offline
Joined: 2004-08-15

> I believe that those that are againist pass by
> reference or multiple outputs had never involve
> in writting serious programs.

Your belief is, of course, incorrect.

> This debate is the same as the debate of operator
> overload. Why not sun just put us (the programmers)
> these options and leave it to us either to use or not.

Because we who write serious programs do so in the real world. We cannot choose not to use or understand language features on a whim. Other programmers and library APIs use features, so we must use and understand them.

"You do not need to use feature X" is an old battle cry for trying to put junk into languages. It is not and never has been a valid argument.

> So here, I peg for somebody to tell me how to get
> multiple (int) values that are unrelated out of a
> method in handy way.

Why do you have methods that return unrelated values? Can you give some examples of such methods?

podlesh
Offline
Joined: 2004-07-26

> #1 It is not your problem and won't affect you. If
> mutiple return parameters are added to Java, why do
> you care? It is a much smaller change than Generics
> for example, but we did not hear as much wailing and
> gnashing of teeth on that. Nobody will force you to
> use multiple return parameters. I don't like
> autoboxing, so I don't use it, but you don't see me
> railing against those that do.

I agree, I don't like autoboxing too (and avoid it as much as possible) and I won't mind if multiple return parameters would be added to java (although there are very serious issues discussed in other threads on this forum)...

but..

"multiple return values" and "parameters passed by reference" are different things! Using pass by reference for multiple return values is hack. Very ugly hack, IMHO.

jwenting
Offline
Joined: 2003-12-02

> I sincerely doubt that not having pass by reference
> is a bottleneck in your application.
>
Indeed. Poor design and even worse implementation are far more likely culprits.
And if not, he can always use what he would consider a "real" language like C++ and pass all the references he wants.

> > Pass by reference is used a lot in many serious
> comercial product.
> Many serious commercial products don't use pass by
> reference at all, e.g. those written in Java.
>
or almost anything else not written in C++ :)

> > Please give me evidence if you believe pass by
> reference is dangous and should keep out of java.
> I believe you need to make a case that it is actually
> needed.

NOOO! He wants it, that should be all the reason the world needs!!!!!

rogerhernandez
Offline
Joined: 2005-02-23

Why do you care so much?

#1 It is not your problem and won't affect you. If mutiple return parameters are added to Java, why do you care? It is a much smaller change than Generics for example, but we did not hear as much wailing and gnashing of teeth on that. Nobody will force you to use multiple return parameters. I don't like autoboxing, so I don't use it, but you don't see me railing against those that do.

#2 A repeating theme I keep reading is that multiple return parameters are not a proper object oriented solution. Our job as software developers is not to come up with proper object oriented solutions, it is to meet our clients' software requirements. Object oriented programming is one of many useful abstractions we use to achieve that goal, but it is only a tool. It is not a silver bullet that solves all problems, and should not be adhered to at the cost of everything else.

#3 There is a very small but significant overhead in creating small objects just to shuttle values back and forth from function calls. In 90% of programs that overhead make no difference whatsoever. In the remaining 10% that deal with processing large data volumes, very high throughput, need very quick response times or do intensive number crunching, it makes a significant difference. If you are not doing that kind of software development then multiple return parameters are not applicable to you.

Please stop insulting others by telling them that they are not doing "proper" object oriented design. In my own case I could not care less about "proper" design, I care about giving my clients stable, correct and maintainable solutions that meet their requirements. OO design is one of the many tools I use to do that.

sjasja
Offline
Joined: 2004-08-15

> #1 It is not your problem and won't affect you. If mutiple return
> parameters are added to Java, why do you care? [...]
> Nobody will force you to use multiple return parameters.

A programmer needs to know the language he uses. He can't just learn a few features and ignore the rest. More features and their interactions with other features = more complex, esoteric, hard to learn, hard to understand, beginner-hostile, bug nest of a language.

Programmers do not live in a vacuum. They use APIs created by others. They read and maintain other programmers' code. Programmers can't just ignore language features they don't like.

"If you do not like a feature do not use it" is not a valid excuse for adding features.

alexanderschunk
Offline
Joined: 2005-03-24

summing this thread i learned the following:

#1 If you are a writing programs using C++ [i]call-by-reference[/i] is a good thing, if you write programs using Java it is a bad thing.

#2 [i]Call-by-reference[/i] should not be part of Java because its not 100% OOP style programming.

#3 Programmers should only worry about programming language concepts they are familiar with and ignore other features that may fit better to a given task.

I may add my opinion on the 3 issues above:

To 1# Since i have learned both C++ and Java i do not really understand what's the matter about using a specific language in a given situation or not. In C++, [i]call by reference[/i] was introduced to be able to change local variable values in a function call:

Consider the following example:

int i = 5;
int j = 10;

void read2ints(int i, int j){
cout << "Enter 2 integers: ";
cin >> i >> j;

}

This function will not work as expected, because the 2 int vars won't be changed keeping their intial values.

But if we change the function parameters as follows, the values will be changed after the cin >> operation:

void read2ints(int& ri, int& rj){
cout<<"Enter 2 ints: ";
cin >> ri >> rj; //read values without &
}

In java we do not need such things because if you write a method read2ints(int i, int j) in Java like so:

public void read2ints(int i, int j){
//read ints
}
it will read the 2 int values and change them according to the values passed over the command line. This is because Java has a completely differen concept dealing with input and output streams and paramter passing.

To 2) Java provides such a wide set of well selected OOP features - Instances, abstract classes, restricted polymorphism, classes - that you are free to use and i never heard anyone claiming that Java should have interfaces or abstract classes because they are also used in C++ or Java should have multiple inheritances because that would meet 100% OOP style. Java has shortcomings and benefits, however, we have to live with them.

To 3) I don't belive any programmer in the world will make use of all existing OOP concepts in his programming career nor in his lifetime. In fact, most developers are concerned with writing a particular type of application or devsuite using some of the many OOP features mentioned above but i do not think this would mean they do not care or not know about other features avaiable. They simple choose the feature that fits best to their application or personal coding style. We should be glad to have that great number of features avaiable and not be restricted to a few only. May be C++ was too overloaded with OOP features not well thought out, but i think Java just offers the right balance of OOP and non OOP features to developers.

kcpeppe
Offline
Joined: 2003-06-15

>
> I may add my opinion on the 3 issues above:
>
> To 1# Since i have learned both C++ and Java i do not
> really understand what's the matter about using a
> specific language in a given situation or not. In
> C++, [i]call by reference[/i] was introduced to be
> able to change local variable values in a function
> call:
>
> Consider the following example:
>
> int i = 5;
> int j = 10;
>
> void read2ints(int i, int j){
> cout << "Enter 2 integers: ";
> cin >> i >> j;
>
> }
>
> This function will not work as expected, because the
> 2 int vars won't be changed keeping their intial
> values.

If your expecation is based on a pass-by-pointer model, then you would be correct. However the key to understanding a language is to learn how it binds values to variables and as well as the visibility and scope of those bindings. Without this understanding, it becomes difficult to know what to expect.

In C/C++ you can have both pass by value and pass by reference. Without the extra syntax & and *

One of the principles of OO that I often see violated is one of responsibility. An object needs to take responsibility for it's internal state. That means no other object should be able take my internal state and modify it. Now unfortunately because of how Java binds objects it is quite easy to violate this. In fact the Java Bean specification even encourages it by requiring get and set methods to be defined for every instance variable. That said, we often need to expose internal state to an external (to us) piece of code. If these values were passed by reference as is the case with the code that you've posted, then you are suggesting that the language make it even easier to violate this principle of maintaining my internal state. In fact with primitives, I'd have very little control over my internal values once I released those values to the greater execution context. These are the exact problems that grind C++ developer productivity down into the ground. This is why Java development is generally 2.5x faster then development in C++. And this why we need to avoid introducing these features into Java.

ramimahdi
Offline
Joined: 2004-05-29

I have realy very simple and silly question.

Should I be expert OO engineer to be able get two irrelated values out of a function.

Why everybody wants to chalenge my design. Should I spent long time make OO design to be able to get those two fucken values out of a method in a reasonable way. What nonesense is this.

What I say is that: a language of the future should be [b]Extensible[/b]. I should be able to make things on the fly. Even if they are not recommended from OO point of view.

I feel right now that I am talking to deaf people right here. My argument is really simple. It must be an option.

I don't care how the JDK engineers are going to handle it if it breaks some java standards. But I cannot beleive that it is impossible.

kcpeppe
Offline
Joined: 2003-06-15

> I have realy very simple and silly question.
>
> Should I be expert OO engineer to be able get two
> irrelated values out of a function.

As it stands right now, you should have software engineering skills to write programs. I doubt that it will remain this way but the current state of technology is that you must understand how computer languages work and why they've been designed the way that they have.
>
> Why everybody wants to chalenge my design.

These people have met the first criteria and are trying to help you reach that point also.

> Should I
> spent long time make OO design to be able to get
> those two fucken values out of a method in a
> reasonable way.

Hold on, no need to use offensive langauge here... What we are trying to suggest is that what you're trying to achieve is a bad idea. Maybe you should learn how to accept these things rather then spouting off like a spoiled child!

>
> I feel right now that I am talking to deaf people
> right here.

No, you are talking to people who don't agree with you and since the context of this forum is where should we take Java... you are the one that needs to back off on the attitude.

sjasja
Offline
Joined: 2004-08-15

> All your assumption is smll object cretion
> won't hurt performance, but do you have benchmark?

I do.

Do you? You seem so worried about object creation speed - have [i]you[/i] timed it before worrying about it?

Of course, if you use proper OO design, you rarely need to return multiple values. Or, for that matter, proper functional design or most any other proper design will get you that too.

My lowly laptop PC can create and collect some 150,000,000 (a hundred and fifty million) objects per second. Test program below; remember to use "java -server".
[code]
public class CreateObject
{
public static void main(String args[])
throws Exception
{
for (int m = 0; m < 5; m++)
doit();
}

static void doit()
{
long start = System.currentTimeMillis();

for (int n = 0; n < 10 * 1000 * 1000; n++) {
new CreateObject();
new CreateObject();
new CreateObject();
new CreateObject();
new CreateObject();
new CreateObject();
new CreateObject();
new CreateObject();
new CreateObject();
new CreateObject();
}

long end = System.currentTimeMillis();

System.out.println((end - start) + " ms");
}
}
[/code]

tlund_
Offline
Joined: 2005-04-21

Microbenchmarks are dangerous. There was a blog or a post recently explaining this.
I think that the JVM can optimise away your code, and thus never create any "CreateObject", since it is never used (referenced anywhere).
(But i'm not an expert on this).
I'll see if I can dig up that blog/post.

EDIT: Found it.
Hope I'm not totally wrong about this:
"As with all benchmarks, there is a significant risk that the compiler will be able to optimize away the whole thing, because it will (correctly) realize that the benchmark code doesn't actually do anything or produce a result that is used for anything. Writing effective benchmarks requires that we "fool" the compiler into not pruning away code as dead, even though it really is."
http://www-128.ibm.com/developerworks/java/library/j-jtp02225.html?ca=dr...

Message was edited by: tlund_

sjasja
Offline
Joined: 2004-08-15

> I think that the JVM can optimise away your
> code, and thus never create any "CreateObject",
> since it is never used (referenced anywhere).

It could but it doesn't. I knew the danger was there, so I checked for that.

u5321007
Offline
Joined: 2003-08-06

> My first language was assembly and much later C/C++.
> I would still suggest you use an OO design, even in
> n C++.

I doubt you suggest because what I see in real world. Pass by reference is used a lot in many serious comercial product. This including a new cuting edge database system wich is designed for store Giga size data and access in very fast speed.

Sure, it's possible to use many other trick to live without pass by reference, but the problem is speed and all other solution I have see is too much redunancy.

I don't need solution wich I can easily do by myself. Please give me evidence if you believe pass by reference is dangous and should keep out of java.

peter_lawrey
Offline
Joined: 2005-02-24

> Sure, it's possible to use many other trick to live without pass by reference, but the problem is speed and all other solution I have see is too much redunancy.

I sincerely doubt that not having pass by reference is a bottleneck in your application.

Creating new objects has minimal impact on most real world applications. Creating a Pair object can take 20 ns or less. You can reuse the object and there is no need to create a new one on each call.

For the rare cases where creating an object makes a difference, it is easy to refactor most application so you don't need to create a new objects.

> Pass by reference is used a lot in many serious comercial product.
Many serious commercial products don't use pass by reference at all, e.g. those written in Java.

> Please give me evidence if you believe pass by reference is dangous and should keep out of java.
I believe you need to make a case that it is actually needed.

peter_lawrey
Offline
Joined: 2005-02-24

For anyone interested, here is an example benchmark.
[code]
public class Main {
public static class Pair {
private A a;
private B b;

public Pair(A a, B b) {
this.a = a;
this.b = b;
}

public A getA() {
return a;
}

public void setA(A a) {
this.a = a;
}

public B getB() {
return b;
}

public void setB(B b) {
this.b = b;
}
}

public static void main(String[] args) {
for (int i = 1; i <= 3; i++)
test(i);
}

private static void test(int n) {
int RUNS = 5 * 1000 * 1000;
Integer i1 = 1;
Integer i2 = 2;

long start = System.nanoTime();
for (int j = 0; j < RUNS; j++) {
Pair p;
p = new Pair(i1, i2);
p = new Pair(i1, i2);
p = new Pair(i1, i2);
p = new Pair(i1, i2);
p = new Pair(i1, i2);
p = new Pair(i1, i2);
p = new Pair(i1, i2);
p = new Pair(i1, i2);
p = new Pair(i1, i2);
p = new Pair(i1, i2);
}
long end = System.nanoTime();
System.out.println("Test " + n + " time to create Pair " + (end - start) / 10 / RUNS + " ns.");
}
}
[/code]
This prints with java version 1.5.0_04 and -Xmx256m -Xms256m
[pre]
Test 1 time to create Pair 11 ns.
Test 2 time to create Pair 9 ns.
Test 3 time to create Pair 9 ns.
[/pre]

boereck
Offline
Joined: 2005-07-17

> Problem with the style you use (multiple return
> arguments via pass by reference) is that it breaks
> one of the base rules of OO: encapsulation. Data
> should be held together in objects, forming logical
> data units.
>
> You should return result object, which contains all
> result data (in this case: index, table). That's the
> "most correct" OO approach.

This is an argument for tuples as a lightweight return-object, instead of call-by-reference or out-parameters (call-by-result ?)

> If the object creation it too much overhead for you,
> use this object as value object:
> void storeTable(Owner owner, int type, BaseTable
> value) {
> value.setIndex(...); //use field if too much
> ch overhead...
> ...
> }

Sorry, I don't understand that.

One advantage of call-by-reference is that you can create a new object and assign it to the parameter, if the parameter is null (instead of throwing a NullPointerException).
In my opinion call-by-reference is not a must-have feature and it can simply be simulated (e.g. by a generic wrapper-class). But I think it would be a nice addition, that could decrease code-complexity in some cases.
The problem with the multiple return values is a little bit different, because there cannot always be used the same wrapper-class (if you want to return everything in one return-object).
Does somebody have papers/links/interviews or something like that where the designers of java themselves explain why they didn't implement call-by-reference?
I am really interested in that.

Message was edited by: boereck

sjasja
Offline
Joined: 2004-08-15

> Does somebody have papers/links/interviews or something
> like that where the designers of java themselves explain
> why they didn't implement call-by-reference?

There is the oft-quoted:

"There is exactly one parameter passing mode in Java -pass by value- and that helps keep things simple."
[i]- The Java Programming Language, by Ken Arnold and James Gosling, 2nd ed, section 2.6.1.[/i]