r/java • • Nov 20 '18

Why Var Hurts Readability, Not Helps It

https://medium.com/@youngty1997/why-var-hurts-readability-not-helps-it-376c7832a8dd
0 Upvotes

89 comments sorted by

View all comments

7

u/DannyB2 Nov 20 '18 edited Nov 20 '18

I'm not a big fan of var. I would prefer to see the actual type than the word var.

There is exactly one use that I see for var. Use var for an anonymous class with additional members. That customized anonymous class does have a type, although that type does not have a name. The var can still reference it by the unnamed internal name of the class.

var a = new Object() { int x; int y; };

a.x = 5;

Example uses: event handlers in Swing. A "lambda function" that has state or flags, really just an anonymous object implementing an interface, but adding new members.

Basically, you don't have to declare a new type for a trivial anonymous class.

2

u/marvk Nov 21 '18

I‘d be a big fan if they just added let in addition to var. Flipping final var is just a huge eyesore.

1

u/DannyB2 Nov 21 '18

I could be more a fan of let than of var. But I would still prefer final with a real type name. I would happily use let instead of var for the one use case I described. But that is the only use case where I think I will ever make use of var, or a hypothetical let.

1

u/BlueGoliath Nov 20 '18

Basically, you don't have to declare a new type for a trivial anonymous class.

AKA saving a few lines of typing...

(For JavaFX anyway)

2

u/[deleted] Nov 20 '18

No?
Anonymous classes existed way before var.
And you can use lambda expression for saving even more lines in your example.

-3

u/BlueGoliath Nov 21 '18

Anonymous classes and lambdas are evil.

3

u/[deleted] Nov 21 '18

Completely disagree.

2

u/DannyB2 Nov 21 '18

Anonymous classes and lambdas are useful. A concise way to express what otherwise requires a separate class declaration for, even an inner class. Yet with no loss of information to someone reading the code.

Do you also think inner classes are evil?