12

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?.

Community
  • 1
  • 1
Oscar Gomez
  • 18,436
  • 13
  • 85
  • 118
  • I think you understand this, but to be sure: in your two example methods the assignment to `obj` is accomplishing nothing at all since the new object isn't used afterwards in the method. – ColinD Jun 04 '10 at 01:59
  • Yes I know this, but thank you for your comment. – Oscar Gomez Jun 04 '10 at 02:04

1 Answers1

10

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
  • 59,111
  • 13
  • 86
  • 103
  • 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 Jun 04 '10 at 02:27
  • @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 Jun 04 '10 at 02:40
  • 1
    @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 Jun 04 '10 at 03:04
  • 1
    @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 Jun 04 '10 at 03:07