1

Because val is similar to final in Java, should most Java object references be marked as final as using val is good practice in Scala?

kiritsuku
  • 52,967
  • 18
  • 114
  • 136
blue-sky
  • 51,962
  • 152
  • 427
  • 752
  • 1
    `val` is only superficially similar to `final` – parsifal Jan 03 '13 at 19:13
  • 2
    [Yes](http://stackoverflow.com/questions/137868/using-final-modifier-whenever-applicable-in-java) – om-nom-nom Jan 03 '13 at 19:17
  • The first time enlightenment dawned on me and I started to use `volatile` all the time. The second time - `final`. The last word - `val` can be considered as Stage 3. – idonnie Jan 03 '13 at 20:46
  • 2
    @idonnie volatile should be used with great responsibility -- afaik, it throws away your cache and thus decreases performance. – om-nom-nom Jan 03 '13 at 20:55
  • @om-nom-nom following your link, have found a confirmation of my though: quick prototype as you can, then refactor to `final`, otherwise guys after you will fill more pain – idonnie Jan 03 '13 at 21:17

3 Answers3

2

Certainly it's good practice to make class variables final in Java, encouraging immutability wherever possible.

As for whether local variables -- method parameters, etc. -- should be marked final when not necessary, that's a question of style. Personally, I feel it tends to clutter things when used, unless it's otherwise necessary (e.g. to make a variable accessible in an anonymous inner class).

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
1

references should be final as often as possible. It allows for greater runtime optimization, and it helps "contractually" ensure that you (or your code's subsequent maintainer) don't change a reference unexpectedly. To me, it's akin to "private" in the sense that you should make things as private as possible. It offers you future flexibility to refactor without affecting other parts of the codebase (minimizes ripple effect).

dashrb
  • 952
  • 4
  • 10
  • 2
    No, it doesn't affect performance. `final` modifier made a difference in early versions of JVMs and now it is discouraged to place final because of performance reasons. – om-nom-nom Jan 03 '13 at 20:44
0

As most of this decisions, the usage of final is a discussion for coding conventions.

I myself make all parameters and variables final if they are assigned only once. I think it increases readability of the code.

Eclipse has a SaveAction to add final where ever possible.

Maybe the keyword helps the compiler to detect possible optimization (or maybe future compilers will be able to use this hint)

MrSmith42
  • 9,961
  • 6
  • 38
  • 49