Hacker News new | ask | show | jobs
by WHoWHo 3018 days ago
From my experience in 20 years of Java, it prevents the reusage of local vars, which mostly is wrong.

   Person p = ....
   p = doSomething(p)
   ...
   p = doSomethingElse(p)
is hard to reason about when it should be

   Person p = ....
   ... lots of code
   Person updated = doSomething(p) 
   ... lots of code
   doSomethingElse(updated)
Which is easier to read and understand. So you might have had bugs that would have been prevented with final, but you didn't attribute to final.
3 comments

I remember bugs that were caused by the exact opposite. If p is superceded by updated then it's not a good idea to have both hanging around in the local scope.

You shouldn't be able to doSomethingElse(p) when you actually mean to doSomethingElse(updated).

So basically, what rust prohibits.
I don't know Rust very well at all, but I believe that Rust would only prohibit that if p and updated were referencing the same thing. If updated was a modified copy of p then I don't think Rust would help. But I could easily be wrong on that.

What would help is splitting the function up so that you don't have multiple named variables representing multiple versions of the same thing in the same scope:

   Person doSomethingAndDots() {
     Person p = doSomething(...)
     ...
     return p 
   }

   main() {
      doSomethingElse(doSomethingAndDots())
   }
If the transformation function consumes p, rather than taking a reference to it, Rust will stop you from using the variable again afterwards.
Rust explicitly allows shadowing, that way you can have it both ways. An immutable variable that can't be reassigned but you can still reuse names.

That is to ease the pain of unwrapping nested types and error-checking intermediate steps so you don't have to come up with new names for each intermediate.

I really like being able to declare immutable variables with ‘let’ in Swift. Java should add the immutable option too. Although, ‘val’ makes more sense considering Kotlin and Scala use it.