Make final behave like var

Remi Forax forax at univ-mlv.fr
Sat Oct 26 16:54:36 UTC 2024


> From: "Kenneth Fogel" <kfogel at dawsoncollege.qc.ca>
> To: "discuss" <discuss at openjdk.org>
> Sent: Saturday, October 26, 2024 5:45:30 PM
> Subject: Make final behave like var

> Just a thought that came up in a reply to a LinkedIn post that contended that
> ‘final’ was useless because the JIT could figure out what was final and what
> was not. I disagreed because I felt it would impact the readability of code. It
> was then that what may be a silly idea struck me. Could the keyword ‘final’
> behave like ‘var’? I do like that you can defer initializing a final variable
> whereas a var variable must be initialized right away. However, if we want to
> encourage a greater use of constant variables (those two words always sound
> like an oxymoron), and reduce decorations then could final be made to work like
> var? I shudder to say this, but could we use the term ‘const’ so as not to
> interfere with existing code. Even have an ‘sconst’ if we want it static, too.

const is already a reserved keyword, even if it is not used (now you know :) ) 
https://docs.oracle.com/javase/specs/jls/se23/html/jls-3.html#jls-3.9 

I really dislike the use of final on local variables for several reasons 
- it makes the code less readable 
- final on local variable is not important, there was no 'final' keyword in Java 1.0, it was added in 1.1 to mark local variable that can be captured in an anonymous class. 
Since 1.8, the compiler computes itself if a local variable is not or not, so the original reason to use final on a local variable has disappear. 
- I can see the point of declaring the parameters final, because debugging a code that changes the value of the parameters is not fun, 
but, it's a weak argument compared to the readability of the code (IDEs and checkstyle detect those cases). 
- final on fields is very important, if you want to create an unmodifiable class and forgot to declare your fields final, you have a publication problem (another thread can see the instance half initialized), so for me, final on local variables acts as a stupid distraction, i want to only see the important "final"s. 

And for final on fields, the behavior from the JIT POV depends on the container, inside a record or a hidden class (the captured variables in lambdas), final really mean final, so it's a kind of a mess. 
As part of valhalla, we want to introduce the concept of strict final fields, a strict final field is a field wich is marked final and initialized before the call to super(), those fields will help the JIT (see https://openjdk.org/jeps/482). 

> Just thinking out loud. Feel free to use my name in vain.

> Ken

regards, 
Rémi 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/discuss/attachments/20241026/2c9cb610/attachment.htm>


More information about the discuss mailing list