Archived

This topic is now archived and is closed to further replies.

[java] method signatures and return types

This topic is 5253 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

just a general programming style question. im sure everyone will feel differently. since you can pass arrays back (sort of, i know its just a reference) from methods, do you guys like to pass arrays back that way or through the passed variables. like: double[] whatever(double[] a, double[] b) { //do whatever to a return a[] } or void whatever(double[] a, double[] b) { //do whatever to a } i see both, and i guess neither is more correct, but i''d like to know what you guys do.

Share this post


Link to post
Share on other sites
References in Java are NOT the same as references in C++. Its a mistake that many programmers make. References in Java are still passed by value.

//this won''t work
public void increaseSize(double[] b) {
//allocate a new array for B
b = new double[b.length * 2];

//b now refers to an array 2x the length of the original
}
//b now points to whatever array it was refering to before.

So if you''re going to modify the reference of the array that is passed to a method, you''ll probably need to return a new array or find some other method.

Hope that made sense.




Share this post


Link to post
Share on other sites
If the method creates a new object (rather very deliberately or innocently such as the example NuffSaid gave) then I return the reference, as well, there's no other way possible in Java.

If the method intends to merely alter an existing object, I always use the void way. To me returning a value suggests something new. Another developer may come along and use my method assuming the return value references a new object and think after the call he's now got two objects, which introduces some subtle bugs.

Then there's the combining of the two, which I'm not too fond of. Java2D does this for BufferedImageOp with the method

BufferedImage filter(BufferedImage src, BufferedImage dest);

If dest is not null then filter will use dest as the new image it's filtering into and also return dest, otherwise it creates a new image and returns the reference to it. Er, that's the intention anyway. That method is found in an interface.

[edited by - tortoise on July 26, 2003 11:38:45 PM]

Share this post


Link to post
Share on other sites