-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Yikes, be careful here! The rule still applies, but for maybe different
reasons.
In the example, both changed values in getFoo will be LOST. Neither
value will be changed from the perspective of the code calling this
method. As long as you simply use those values within the scope of the
method, you'll be okay. If you expect to get a value back, you'll be in
for a surprise.
The int is passed by value, so the a_value that you're modifying is a
copy on the stack, and the stack frame for this method is lost when the
method returns and any changes to that int are lost with it. The Object
ref is also copied onto the stack, so when the method returns, the
reference to the new Object is lost, and with no reference to the object
the new Object will be garbage collected.
Another good (non-compiling semi-pseudo code) example:
public void someMethod() {
List newList = null;
initializeList(newList);
newList.get(index); // OOPS! Null pointer!
}
public void initializeList(List newList) {
newList = new ArrayList();
... set some values ...
}
A proper compiler error may catch this error.
~Joe
Edward Sumerfield wrote:
> Is the warning "The parameter value should not be assigned" still valid in
> Java?
>
> public void getFoo(int a_value, Object a_object)
> {
> a_value += 1; // WARNING
> a_object = new Object(); // WARNING
> }
>
> It has always been good programming practice to avoid assigning parameters
> because in C/C++ you might be setting a pointer that the caller would not
> know had changed.
>
> In java it is not possible set the object references that are passed in and
> the primitive types are passed by value so what is the danger?
>
> I propose that the old bad practive rule be revoked in the light of better
> languages?
>
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.3 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org
iD8DBQFE0Ndnx1T2M+8Q7OYRAhIbAJ9Rn2Z63b1y+DNxfp4Nac/SbG1ycwCdHqNv
PzlnsS0Q/PunvVOiJaYIo0U=
=9ocX
-----END PGP SIGNATURE-----
|