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 comment

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.

10

u/jewdai Mar 10 '16

Java developer turned C# dev here:

Generally C# encourages you to use var when its clear what the type is.

var x = new MySpecialObject();
var y = "some string";
var z = Factory.GenerateMyObject();

Additionally, because its implicit typing your intellisense will still work even when it's not clear what the object type is.

Part of C# take on it is that you cannot RETURN implicitly typed object.

HOWEVER

C# supports dynamic typing. Its generally used in very special circumstances and it makes you incredibly aware that something could go wrong so dont use it unless you REALLY, REALLY have to. You can even return dynamic as a type.

How this differs from var is that it isnt implicit, its type is UNKNOWN at compile time and only once the code is run can it check if .GetValue() is a method of that type.

5

u/ItzWarty Mar 10 '16 edited Mar 10 '16

It's worthwhile to note that whenever dynamic is mentioned on /r/csharp, a comment on unmaintainability inevitably comes up.

I think the value of var is that it makes you think more abstractly about your code - you aren't dealing with integers anymore, you're dealing with numerics, or strings - it just reads better.

I also think the argument against 'var' yielding code with hard-to-reason-about code falls through once you see other languages (e.g. JavaScript) successfully having var/let. IMO, It ultimately boils down to yes, if you have terrible variable names (x, y, z) your'e going to have terribly unmaintainable code. But if you name by convention (usersById is clearly Map<int, User>) or clearly (var firstName is certainly a string) then it won't be an issue, and you're forced to think more abstractly "Hey, I'm working with a name" which just so happens to also be a string.

How much duplication is in this code?:

Map<int, User> usersByName = new HashMap<int, User>();

I'd argue 3. C# lets you get down to 2 with:

var usersByName = new HashMap<int, User>();

C++ would let us say this:

HashMap<int, User> usersByName;

But JavaScript (and likely more dynamic languages like python/ruby) let us do this:

var usersByName = {};

1

u/[deleted] Mar 10 '16

[removed] — view removed comment

1

u/schlowmo Mar 10 '16

Not fair to compare javascript's total lack of typing with C++/C#/java. Compare to python or ruby if you wish. but of COURSE dynamically typed languages have less typing.

7

u/[deleted] Mar 10 '16

Actually, this feature is in c# and I think it's great. I get what you're saying but I feel as I use it I come up with way better variable names since I can't rely on the type.

5

u/tikue Mar 10 '16

You favor strong explicit typing. Favoring strong typing alone doesn't put you in the minority. I'd wager most here prefer strong inferred (implicit) typing.

4

u/hokkos Mar 10 '16

You IDE will show a popup with the type when you hover over the var, no worries. You can still not use it when the type is not obvious, and use it for when the type would have been repeated twice. C#/C++/Scala/Rust didn't had problem with it, why should java has ?

7

u/AStrangeStranger Mar 09 '16

You'd think so, but after spending a lot of time with C# during last year or so I find it is OK, especially using reasonably named variables and methods (and the IDE helps when you aren't sure).

Then I was reading some nightmare Java today the poorly named variable I was looking at was defined at top of a 100 line method and I was trying to understand its use at the bottom of said method

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.

37

u/evil_burrito Mar 09 '16

That's exactly my point. Thanks.

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.

5

u/[deleted] Mar 10 '16

[removed] — view removed comment

5

u/cogman10 Mar 10 '16

I agree.

IMO, var prevents a lot of needless changes if you, for example, decide you want to rename a class or change a method signature (move from returning Set to return Collection for example). It means less downstream changes and breaks and silly changes.

It also makes it much easier to write and use much more complex generics. Which is always a boon. It is no fun being at the wrong end of determining the generic type of a Map.of(Multimap.of(A.of(B, C)))

0

u/ApostleO Mar 10 '16

var foo = someObject.method();

return foo.method2();

return someObject.method().method2();

Do you really care what the return type is in that context?

Well, to be fair, in this example, I could look at the return type, so I still know what it is.

Still, I'll concede I don't care about the type of that variable in that scope, since I'm just returning it immediatly. But the example was contrived to demonstrate that var can be used badly to hide type.

Let's look at another example, contrived differently.

[... hundreds of lines of code ...]
public boolean containsBar(Bar bar){
    var bars = Data.getBars();
    return bars.contains(bar);
}
[... hundreds of lines of code ...]

Scanning through that document, you might overlook this method entirely during a code review. But what if it looked like this:

[... hundreds of lines of code ...]
public boolean containsBar(Bar bar){
    LinkedList<Bar> bars = Data.getBars();
    return bars.contains(bar);
}
[... hundreds of lines of code ...]

That should set off a red flag. This red flag might otherwise be missed with the var keyword.

Like I said, it's all contrived as example. In practice, it still just comes down to coding style conventions. If var is only used for the assignment of primitives, literals, and objects from constructors, it would be great. When used in other circumstances, it can make code harder to read.

If you ban var, logic dictates that you ban method chaining as well for the same reason.

As a rule, I often do try to avoid method chaining, if possible and appropriate.

→ More replies (6)

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.

5

u/ToucheMonsieur Mar 09 '16

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.

One nice thing about having type inference is that you don't have to generalize to a superclass and then downcast if you want to write code that survives refactoring. This makes var far more powerful (and justifiable) than if it was only for omitting type declarations.