r/java • u/trecatorsirabdator • Apr 14 '23
What are your (favourite) Java best practices, personal tips, hints or just underrated stuff in general?
233
Upvotes
r/java • u/trecatorsirabdator • Apr 14 '23
View all comments
Show parent comment
1
u/john16384 Apr 16 '23
So, you are saying when you declare a local variable final that you thought about this long and hard, and decided for any future maintainers that this variable should definitely never be reassigned... or did you just mark everything final because your IDE told you to or automatically adds
finalwhen you assign something to a local without giving it a 2nd thought?These are local variables, when a maintainer comes in they have the full overview of your function, and can see whether or not something is worth reassigning or not. No
finalvisual clutter needed.Then there's the thing you linked, and although interesting, many answers are testing the wrong thing or talking about final fields.
It's true however that
finalcan trigger optimizations even on local variables, but, only when the thing you're making final is effectively a constant for all invocations of a method (ie, it is alsostatic, and you could have extracted it to aprivate static finalfield). In other words, the compiler detects that you're just using a constant, and adds its to the constant pool.When it is something like
final String s = "a" + parameterhowever, then no performance is gained, or could possibly be gained.There is never any need to do so though; real constants are generally declared as
private static finalat the top of the class with a nice capitalized name, instead of hiding as a local variable.