users
[Top] [All Lists]

Re: [cinjug-users] IDE Warning - Parameter value should not be assigned

To: "users@xxxxxxxxxx" <users@xxxxxxxxxx>
Subject: Re: [cinjug-users] IDE Warning - Parameter value should not be assigned
From: Joe Fox <joe.fox@xxxxxxxxxxxx>
Date: Wed, 02 Aug 2006 12:48:39 -0400
Delivered-to: mailing list users@cinjug.org
In-reply-to: <6a216ba20608020750v496e606eh72da2bd5deb9f907@mail.gmail.com>
Mailing-list: contact users-help@cinjug.org; run by ezmlm
References: <6a216ba20608020750v496e606eh72da2bd5deb9f907@mail.gmail.com>
User-agent: Debian Thunderbird 1.0.7 (X11/20051019)
-----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-----

<Prev in Thread] Current Thread [Next in Thread>