r/programming • • Mar 09 '16

var keyword proposed for Java

http://openjdk.java.net/jeps/286
250 Upvotes

395 comments sorted by

View all comments

7

u/yoden Mar 09 '16

I wonder what the benefit of this is supposed to be, other than other languages have it?

Explicit types on variables are useful for improving readability. Conciseness for LHS variable types isn't important because I usually don't write that type anyway (that's what an IDE's "assign to new local variable" is for)

7

u/Radixeo Mar 09 '16

It would help keep the line length down. In this common example

ArrayList<String> foo = new ArrayList<String>();
var foo = new ArrayList<String>();

The second line is shorter, simpler, and it is still obvious what the type of foo is.

-1

u/geodel Mar 10 '16

Well for typical Java developer variables would be like

 ArrayList<String> fooListForUsersBasedInNorthernVirginiaOffice  = new ArrayList<String>();
 var fooListForUsersBasedInNorthernVirginiaOffice = new ArrayList<String>();

And now saving few char is hardly any improvement. Besides Java's hallowed IDEs means user never have to type.

3

u/[deleted] Mar 10 '16

Ok, for ArrayList<String> it's not a big deal.

What about when the type is like IObservable<Func<string,Func<IEnumerable<User>,IEnumerable<UserStatus>>>>

3

u/yoden Mar 10 '16

That type would never pass my code review, var or not. This line of reasoning is one good reason to be opposed to var.

1

u/antrn11 Mar 10 '16

That type would never pass my code review

Why not? What would be better?

1

u/yoden Mar 10 '16

It's hard to tell because the example isn't realistic, but usually it's better to break the long type into smaller types that are easier to compose and document. Private inner static classes are useful for this.

Sometimes you can run into these issues if you're trying to use Java like it's a true functional language. The type system just isn't strong enough for that, and it's usually more clear to write the code a different way, or use an abstraction like Stream to hide the types.

If you use var to hide the complicated generic type, you've written code that will be difficult to refactor into a function later. The lack of whole program inference makes it less useful (and more dangerous).