|
Val's Blog
Lots of stuff for Web 2.0 freaks and Java addicts
|
|
|
Albert Einstein: "Intellectuals solve problems: geniuses prevent them." |
[ Login ] |
|
It's no secret that primitive and reference arguments are always passed by value in Java. This means that a copy of the primitive value, respectively a copy of the reference to an object, is actually passed on to the method as depicted in the small example below.
In clear, every primitive or reference value that gets passed to a method usually goes unaffected and the caller can be sure that the value he passed has not been changed in the body of the called method. The designers of the Java language originally decided not to include pass-by-reference semantics into the language in order to prevent some obscure things that have been known to happen in C++ programs to occur within your Java program. Briefly, in Java all parameters are IN parameters, which doesn't mean that you cannot invoke methods on the reference you get in order to alter the state of the object!! Now, there are some areas like distributed computing where it might be sometimes desirable to pass objects around by reference. For instance, CORBA has the concept of "Holder" classes to simulate the behavior of INOUT or OUT parameters. Holder classes usually contain a reference to some value that the caller wants to be changeable from within the called method. By using OUT or INOUT parameters, a method may possibly "return" several values. This wrapping trick can help you bypass Java's requirement of having at most one value being returned from a method call. A small academic example illustrates this concept below:
You could as well use an On the other hand, you might ask yourself whether you really need to return several values from your method calls. Usually, when this case arises, it is usually a sign of poor object-oriented design. Using OUT or INOUT parameters makes your code harder to understand and to maintain. The semantics of the Java language is usually sufficient for solving 99.9% of the problems you may come up with. So maybe, you might have to rethink your design and see if the values you have to return might not be better bundled in some new class... Personally, I must admit that I have never really used this technique in any of my applications and I don't think it brings much business value, but it is good to know that it is possible to simulate pass-by-reference semantics and to be able to "return" more than one value from a method call. Not all inventions and findings are useful ;)
TrackBacks[0]
Comments[0]
Posted by val on May 21, 2004 9:51:27 AM CEST
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Content © Val | Powered by Pebble 1.9.1 |