Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java assigning a new value to a parameter, is this considered a bad practice?

I have read the question here: Is it problematic to assign a new value to a method parameter?. However it is not clear to me if doing something like:

public void myMethod(Object obj) {
    doSomething(obj);
    obj = getNewObj();
}

or:

public void anotherMethod(Object obj) {
     obj = doSomething(obj):
}

This is basically just to avoid declaring a new local variable, is this worth it?, is this seen as a bad practice?.

like image 939
Oscar Gomez Avatar asked Jun 04 '10 01:06

Oscar Gomez


People also ask

Is it bad practice to modify parameters?

It's considered bad practice in general, though some people overlook it as you can see in the other answers. For parameters like primitives that are directly passed in by value, there is no advantage in overriding the original variable.

Can you change the value of a parameter in Java?

Pass-by-value means that when you call a method, a copy of each actual parameter (argument) is passed. You can change that copy inside the method, but this will have no effect on the actual parameter. Unlike many other languages, Java has no mechanism to change the value of an actual parameter.

Can we assign a value to parameter?

Assigning a value to a parameter can be done in the following ways: From the command line using the -define along with the appropriate parameter and value. A separate -define option is required for each parameter you want to run.

How do you assign a new value to a variable in Java?

type variableName = value; Where type is one of Java's types (such as int or String ), and variableName is the name of the variable (such as x or name). The equal sign is used to assign values to the variable.


1 Answers

This is a bad practice. You will be hard pressed to find a scenario where the sacrificed readability is worth it. This will be especially confusing to anyone who doesn't understand Java's "pass by value" policy, which sadly is a lot of people.

like image 181
dbyrne Avatar answered Oct 16 '22 23:10

dbyrne