views:

159

answers:

2

I have read the question here: http://stackoverflow.com/questions/2229389/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?.

+4  A: 

Performance 0, Readability -1. I wish eclipse could add final tags automatically.

Skeptic
+1 for always having `final` for method parameters. Though if it makes the method signature more readable is doubtful.
Pindatjuh
+5  A: 

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.

dbyrne
A "lot of people" sampled from which population? I think this depends a lot on the context. What matters is the level of competence of those who will inherit my code. When writing code in a professional setting, I think it reasonable to assume my successors know how method parameters are passed. In contrast, I would not assume that when posting code as part of a tutorial on - say - a game programming website.
meriton
@meriton, I find it true of programmers who may be very experienced professionally, but new to Java and coming from a backgroud of a pass-by-reference language (at least where it was an option).
Yishai
@meriton I work for a large corporation and have come across plenty of professional java developers who don't understand this concept. I'm not trying to condone it, but at a lot of companies its a reality.
dbyrne
@meriton I do agree with you that its fair to assume your successor will understand basic java concepts, but I just don't see the payoff in this particular case.
dbyrne