问题
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?.
回答1:
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.
回答2:
Performance 0, Readability -1. I wish eclipse could add final tags automatically.
来源:https://stackoverflow.com/questions/2970984/java-assigning-a-new-value-to-a-parameter-is-this-considered-a-bad-practice