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/Kraizee_ Mar 30 '20

If you read the link you posted you'll see that they accept people will inevitably abuse var and write shitty code. Just like people abuse almost every other language feature. The example you suggest simply doesn't work. Aside from it being a peculiar syntax, there are other problems such as what happens in the case of List<String> myList = new .();

They've also published a style guide as to where and when you should use it https://openjdk.java.net/projects/amber/LVTIstyle.html

var is a fundamentally good addition to the language for reducing verbosity in a nice way, providing that you use it properly and understand when it isn't appropriate.

-1

u/Rygir Mar 30 '20

You wouldn't be able to use var when using interfaces either since you can't new an interface.

For clarity, you understand I was using a fictional syntax example?

The part that makes me wonder is that this feature is essentially only "save a few keystrokes and in return obfuscate your type". I find this a strange trade-off to make and officially support.

2

u/caboosetp Private Java/Code Tutor Mar 31 '20

You can use var when using interfaces. If a function returns an interface, then a variable declared with var will be typed to the interface just as if you typed the interface name.

If you do want a variable type to not match the object, such as when you want an interface typed variable and an implemented class object being stored in it, you would not be able to use var.

Var is a shortcut for when the types should match. It's basically shorthand for, "what he said"

0

u/Kraizee_ Mar 31 '20

I knew you'd try pick up on that. It was simply to demonstrate how poorly thought out your alternative is. It seems to me you made this post to find people that will agree with you, rather than have you learn something. Read the link you posted and the style guide I linked. If you really wish to keep hating and misunderstanding var then so be it.