Hacker News new | ask | show | jobs
by ticking 4104 days ago
Just do

  public foo(Bar bar) {
        bar = baz(bar);
        //Lots (10+ lines) of code
        return finishProcess(bar);  //Note, this should have been updatedBar.
  }
nothing prevents you from reusing the variable name. The point about immutability is that the objects themselves don't change.
1 comments

Alas, our style guide insists on final variables...
In my opinion, there is a reason for that. Consider the example above, slightly changed:

    public foo(Bar bar) {
        bar = baz(bar);
        //Lots (10+ lines) of code.
        bar = qux(bar);
        //Lots (10+ lines) of code.
        return finishProcess(bar);  
    }
It is hard to spot the second reuse of variable bar. This can make code harder to understand; it's a lot easier to just look at the point of definition of a variable and assume it never changes. At least, that is why I tend to use final when writing Java, and val when writing Scala.

Of course, usually when adding final to messy Java code I'm trying to understand, this ends up telling me that the whole piece of code was fragile, hard to understand and in dire need of a refactoring. All of which makes final useful to me.