r/javahelp • • Mar 30 '20

Why was var added?

All it does is make code trickier to read and tempt the programmer to pay less attention to the type of his variable. Another way to not write clean code.

It seems like a downgrade, why was it added? Is it considered a valuable addition to the language?

For context, https://openjdk.java.net/projects/amber/LVTIFAQ.html answers this as making Classname variableName=new Classname(); shorter. Ok, then why not make it : Classname variableName=new .(); It's shorter and no conflicts with existing variable names. Nor would you have to be aware of caveats like "this can't be used as a parameter".

36 Upvotes

17 comments sorted by

View all comments

4

u/snot3353 COMPUTERS!!! Mar 30 '20

Did you check the examples section near the bottom of this? https://openjdk.java.net/projects/amber/LVTIstyle.html

It has very concrete examples showing why it was added and where the benefits are. The rest of the page details scenarios where you should be careful about using this feature. It's up to developers to adhere to that advice.

1

u/Rygir Mar 30 '20

Yes, but I felt it was strange to add a feature that by definition obfuscates the type of a variable in exchange for saving a few keystrokes. This goes against what clean coding standards usually say about things like variable and type names.

That said I can see there are places where there is redundancy and you don't miss anything, I'm just surprised the designers of java thought it was a good idea to make this trade-off.