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

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.

4

u/cogman10 Mar 10 '16

Right, but this is generally caught by the compiler if there is really something wrong with it.

If I say

var foos = object.doThing();
for(var foo : foos)
{
  foo.action();
}

I can quickly deduce from looking at this code that foos is some sort of collection of foo and foo does some sort of action.

The beauty of this code is that object.doThing() is now free to change its return type to any sort of iterable without breaking downstream code. Depending on how they handle the imports, Foo can move all over the package structure or even be changed to a new class Bar so long as it keeps the same contract. All of this will be caught by the compiler if there is an issue, which means the caller will have a weaker dependence on the callee's method signature (A win IMO).

4

u/ApostleO Mar 10 '16

Right, but this is generally caught by the compiler if there is really something wrong with it.

It's true. var is perfectly fine by the compiler. As I've said above, var is only a problem for readability, and only a problem when abused.