Timeline for In Java, should I use "final" for parameters and locals even when I don't have to?
Current License: CC BY-SA 2.5
8 events
| when toggle format | what | by | license | comment | |
|---|---|---|---|---|---|
| Sep 19, 2023 at 11:25 | comment | added | Gary Gregory | Use final to communicate intent: garygregory.wordpress.com/2013/01/26/the-final-kiss-in-java | |
| Jul 4, 2020 at 18:33 | comment | added | PlexQ | Except it really doesn't do that - no in a useful way. What you really want is an immutable marker, which doesn't exist. You can pass a final object, and call all the setters you like; java won't stop you, which honestly, makes final pretty much useless. Also - reassigning the input parameters is bad, but mutating the object passed in is worse. reassigning the name of the variable, honestly, if you're method is short; you won't ever do that anyway; so again - useless. | |
| Oct 23, 2019 at 14:50 | comment | added | blubberdiblub | The visual clutter will be greatly reduced when using syntax highlighting. I mark my locals that are assigned only once - and that I want to be assigned to only once - with final. That may be most of the locals, but clearly not all. For me there is no "happens to never change". There are 2 clearly separated kinds of locals in my world. Those that aren't ever supposed to change again (final) and those that must change as a result of what the task at hand dictates (of which there are very little, making the functions pretty easy to reason about). | |
| Oct 11, 2017 at 8:30 | comment | added | christopheml | final states intent, which is usually a good thing in a piece of code, but it comes at the price of adding visual clutter. Like most things in programming, there is a trade-off here: is expressing the fact your variable is only going to be used only once worth the added verbosity? | |
| Aug 26, 2016 at 4:19 | comment | added | user949300 | Is the "intent" that the variable will never change, and that your code relies on that fact? Or is the intent "it just so happens that this variable never changes so I'm marking it final". The later is useless and possibly harmful noise. And since you seem to advocate marking all the locals, you are doing the later. Big -1. | |
| Aug 26, 2016 at 2:21 | comment | added | Andres F. | @eddieferetro Disagreed. The keyword final states intent, which makes the code more readable. Also, once you must deal with real-world code, you'll notice it's seldom pristine and clear, and liberally adding finals everywhere you can will help you spot bugs and understand legacy code better. | |
| Mar 3, 2016 at 14:46 | comment | added | eddieferetro | If your method is clear and does only one thing the reader will know too. Final word only makes the code unreadable. And if its unreadable its much more ambiguous | |
| Feb 16, 2011 at 8:44 | history | answered | J.K. | CC BY-SA 2.5 |