Skip to main content

Using parameters in a method

3 replies [Last post]
zscipio
Offline
Joined: 2008-11-08
Points: 0

Given a method

M(int theParameter)

Is it better to use theParameter through out the method or save the
parameter in a local variable and use the local variable throughout
the method?
int localvariable = theParameter;

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
dan_codrean_ro
Offline
Joined: 2012-05-21
Points: 0

In my opinion it is better to use a local variable because:

1. You don't alter the original passed parameter, and it can be used for later purpose in that function.

E.g.

M (int theParameter) {
int currentValue = theParameter;

// do something
if(...) {
// alter currentValue
} else {
return theParameter.
}
}

zscipio
Offline
Joined: 2008-11-08
Points: 0

I also have the opinion that it is better to use the local variable but I am looking
for a concrete reason to do so.

grelf
Offline
Joined: 2007-11-14
Points: 0

A local copy is always made automatically so in the previous reply there was never any danger of altering the outside value. However (really important) that was because the value was of a primitive type, int. In the case of any object type a copy is still made automatically but of course it is only a reference that is copied, so it still points to the original object outside the method. Therefore to avoid any risk of altering the outside object you must CLONE the object inside the method. In most cases that is really an unnecessary overhead as long as you are aware of what is going on.
(In JavaScript it is important for performance to make local copies of parameters to avoid the interpreter having a possibly long search for them each time but that is not the case in Java.)