r/java • • Mar 09 '16

var keyword proposed for Java

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

312 comments sorted by

View all comments

Show parent comments

26

u/evil_burrito Mar 09 '16

I do understand that.

My point was that:

var foo = whatevs

is more difficult for humans to read while going through somebody else's code.

12

u/covercash2 Mar 09 '16

It seems safer than that in the article.

More like:

var foo = "string";
var foo = 1;
var bar = 1.0;
var biz = 1f;

We all know what those will compile to. Anything else will have to be declared explicitly, though only once:

var object = new ObjectClass();

instead of

ObjectClass object = new ObjectClass();

Although, I agree with the sentiment that a superclass should be used in a lot of cases, and that fudges with this var syntax a bit.

86

u/ApostleO Mar 09 '16

The problem still arises when you find yourself staring at a line like...

var foo = someObject.method();

Let's say you are doing a code review, not in your IDE at the time. You now have to track down the return type of that method to know what 'foo' is.

1

u/covercash2 Mar 09 '16

Fair enough.

For me, I'd use IntelliJ and C-hover to get the return type. M maybe just not use var this way?

edit: not in my IDE, just got that.

11

u/ApostleO Mar 09 '16

maybe just not use var this way?

Oh, definitely. I would consider this bad practice, for sure.

Java just seems to have this tendency to make good coding practice a feature of the language. For instance, requiring that the class name matches the filename.

The 'var' keyword is, unfortunately, very easily abused to make code less readable, rather than more readable.

That being said, when it is used well, it is actually much nicer to read. And while we are on a similar subject, the 'dynamic' keyword (ex: in C#), is quite useful in certain circumstances to make code much easier to understand, but when abused it can make code incomprehensible.