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?.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With