[bisq-network/style] Do not declare local variables as final (#11)

Chris Beams notifications at github.com
Wed Jun 6 09:10:38 UTC 2018


It is highly desirable to declare member variables (both static and instance) as `final` in order to advertise and enforce the statelessness and immutability of a given class. It is, however, _not_ desirable to declare local variables as `final` for the following reasons:

1. It is not the idiom in Java to do so. This is not to say that people never do it, but that if you scan the majority of large, popular open source Java codebases, you will find that most local variables are _not_ declared `final`, and that where they are, it is done in a way inconsistent with the rest of the codebase.

2. There is typically no need to declare local variables as final. There are certain cases, such as when a variable is declared and then subsequently used within an anonymous class, but this is rare, and even more rare since Java 8 and lambda expressions, which transparently handle local variables as "effectively final" without any explicit `final` modifier necessary.

3. If final is "necessary" because you want or need to prevent mutation, your method is probably too complex. Methods should be simple and typically quite short. There should be no need to "enforce" immutability of a local variable in the context of a method. Its purpose should be obvious, and it should be obvious if overwriting the value of the variable is the wrong thing to do.

4. Applying the `final` modifier to local variables creates line noise without creating any value. The use of `final` on local variables is doubly distracting to the reader, (a) because it is that many more characters that the reader needs to parse and (b) because as noted in (1) above, it is non-idiomatic to see, meaning that it catches the reader's eye all that much more, and makes them wonder (needlessly) "why is this variable declared `final`?", only to eventually realize that it didn't need to be final at all, and that this modifier was just a waste of their time.

5. Java 10 introduces the reserved type name `var` for [convenient declaration of local variables](https://dzone.com/articles/finally-java-10-has-var-to-declare-local-variables), but there is no way to declare a `var` as final (in Scala, for example, this is done with a distinction between `var` (mutable) and `val` (immutable) declarations). This means that in Java 10, it will become even _less_ idiomatic to see `final` local variables, and that you'd need to really go against the grain to declare them that way.

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/bisq-network/style/issues/11
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.bisq.network/pipermail/bisq-github/attachments/20180606/45186334/attachment.html>


More information about the bisq-github mailing list